React and Redux notes
As a starter for web programming, here notes my discovery for React and Redux.
React is a component-based, reusable framework for developing web frontend. A React component renders its contents if its external properties or internal states are changed, consider an editor component with its own property and state:
However, if a property shall be shared among lots of components, it is hard to propagate this property to all components in a top-down manner. E.g., an editor component wants to trigger the boolean property editing, and this property reflects to lots of components including the parents of editor component, the property need to be callbacked to parent components, and be propagated to other child components.
Redux provides a global state machine to solve this pain point. A Redux store provides multiple self-maintained states, which can be injected into a React component. To change the states of a store, a React component should dispatch the action to the store.
For instance, components in an editor component may dispatch an action edit_start, an editor reducer is responsible for updating the state of the store, then the React component can subscribe the store to re-render if the state of the store is changed:
However, dispatch, subscribe and getState are inconvenient to use, Redux provides connect method to mount these functions to the properties of a React component:
For more common case, an action is often an asynchronous task and this cannot be adapted to Redux’s framework. We need Redux-thunk to help solving this problem:
Here we completed the study of React Redux! Followed by some useful tools about Redux:
For universal(isomorphic) rendering, the React component will be rendered on both server and client side. Consider we have a loadAuth action which is an asynchronous task, we want the auth data preloaded even at the initial server side rendering. In this case, Redux-async-connect works to delay the rendering after the data is loaded. The usage of asyncConnect is the same as connect.
Still lost the form data while routing to another page? Try the React-form to keep the form data in Redux store.
This tool can display/hide the state machine of your Redux store by a hot key:
References:
React: https://facebook.github.io/react/
React-Redux: https://github.com/reactjs/react-redux
Redux-thunk: https://github.com/gaearon/redux-thunk
Redux-async-connect: https://github.com/Rezonans/redux-async-connect
Redux-form: http://redux-form.com/6.2.1/
Redux-devtools: https://github.com/gaearon/redux-devtools
Universal(Isomorphic): https://github.com/erikras/react-redux-universal-hot-example