-
Notifications
You must be signed in to change notification settings - Fork 8
Central State ‐ Redux Store
This app uses a central state managed by Redux. The Redux state is accessible in React components if the component is exported using connect
. For example:
export default connect(mapStateToProps, mapDispatchToProps)(TableOfContents);
Redux state property values are accessible by calling mapStateToProps
.
For example:
function mapStateToProps(state) {
return {
message: state.message,
history: state.hashManager.history,
};
}
The returned object is mapped to the props
of the component.
Similarly, changing values of the Redux state can be done by calling mapDispatchToProps
.
For example:
function mapDispatchToProps(dispatch) {
return {
onAddNewRule: () => dispatch(changeEditMode(-1, true)),
};
}
In the above snippet, onAddNewRule
is a new function defined here, dispatch
is a Redux function, and changeEditMode
is an action function defined in actions.js
.
Actions are functions defined to update the Redux state. The return value of an action is an object with type
and data
properties. The type
value is used to specify the update type, and the data
object contains the updated values. The values of the type
properties are stored in reduxStoreConstants.js
under reduxStoreActions
.
For example:
export const updateWS = (ws) => {
return {
type: reduxStoreActions.action_new_ws,
data: {
ws: ws,
},
};
};
Reducers are responsible for updating the Redux state. In this app, there is only one reducer, located in reducers.js
. The reducer function returns the modified Redux state.
const reducer = (state = JSON.parse(JSON.stringify(initial_state)), action) {...}
The initial state of the Redux state is stored in initialState.js
as initial_state
.
The reducer function is implemented as a switch/case block over the type of actions.
One important rule is that the returned state should be a new object. Therefore, it should be created using Object.assign({}, state, { * new values * })
.
Another internal rule is that the Redux state has a property named message
. This property should always be updated with one of the values defined in reduxStoreConstants.js
under reduxStoreMessages
. The reason is that in many cases, components update their states based on the message
value.
For example:
case reduxStoreActions.action_new_ws:
return Object.assign({}, state, {ws: action.data["ws"], message: reduxStoreMessages.ws_msg});