The whole state of your app is stored in an object tree inside a single store. The only way to change the state tree is to emit an action, an object describing what happened. To specify how the actions transform the state tree, you write pure reducers.
import { createStore, combineReducers } from "redux";
/**
* This is reducer, a pure function with (state,action) => state signature.
* It describes how an action transforms the state into the next state.
*
* The shape of the state is up to you: it can be a primitive, an array,
an object, * or even an Immutable.js data structure. The only important part is that
you should * not mutate the state object, but return a new object if the state changes. * * In this example, we use a `switch` statement and strings, but you can use
a helper that * follows a different convention (such as function maps) if it makes sense
for your * project. */
an object, * or even an Immutable.js data structure. The only important part is that
you should * not mutate the state object, but return a new object if the state changes. * * In this example, we use a `switch` statement and strings, but you can use
a helper that * follows a different convention (such as function maps) if it makes sense
for your * project. */
// User operation reducer
function userOperations(state = "Rahul", action) {
switch (action.type) {
case "changeUsername":
return "Ananya Choudhary";
default:
return state;
}
}
// Counter reducer
function counter(state = 0, action) {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
}
// Combine more reducer's into one
const allreducer = combineReducers({
userOperations,
counter
})
// Create a Redux store holding the state of your app.
// Its API is { subscribe, dispatch, getState }.
let store = createStore(allreducer);
// You can use subscribe() to update the UI in response to state
changes.
changes.
// Normally you'd use a view binding library (e.g. React Redux)
rather
than subscribe() directly.
rather
than subscribe() directly.
// However it can also be handy to persist the current state in
the localStorage.
the localStorage.
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: "changeUsername" });
// The only way to mutate the internal state is to dispatch an
action.
action.
// The actions can be serialized, logged or stored and later
replayed.
replayed.
store.dispatch({ type: "INCREMENT" });
// 1
store.dispatch({ type: "INCREMENT" });
// 2
store.dispatch({ type: "DECREMENT" });
// 1
Comments
Post a Comment