1. What is Redux
Official explanation: Redux is a predictable state container for JavaScript apps. This means that Redux is a predictable state container for js applications
2. Why use Redux
The following illustration shows how parent-child components communicate when Redux is not used and when Redux is used
In the absence of Redux, if communication is required between two components (non-parent-child relationships), multiple intermediate components may be required to messaging for them, which wastes resources and complicates the code.
Redux proposed a single data source Store to store state data. All builds can modify the Store through Action s or get the latest state from the Store.Using Redux can solve the communication problem perfectly between the components.
3. How to use Redux
Here is an example of a TodoList implemented with Redux
Store:Create a store to store state data
//store/index.js import { createStore } from 'redux' import reducer from './reducer'; const store = createStore(reducer); export default store;
Reducr: Returns a new state to the store based on the incoming action
//reducer.js const defaultState = { inputValue: '', list: [] } //Reducr accepts state but cannot modify it. A deep copy of the state is required export default (state = defaultState, action) => { if (action.type === 'change_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.inputValue = action.value; return newState } if (action.type === 'add_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.list = [...state.list, state.inputValue] newState.inputValue = ''; return newState; } return state; }
//TodoList.js import React, { Component, Fragment } from 'react'; import store from './store'; class TodoList extends Component { constructor(props){ super(props) console.log(store); this.state = store.getState(); this.handleInputChange = this.handleInputChange.bind(this); this.handleList = this.handleList.bind(this); this.btnClick = this.btnClick.bind(this); this.handleStoreChange = this.handleStoreChange.bind(this); store.subscribe(this.handleStoreChange) } handleStoreChange(){ this.setState(store.getState()); } handleInputChange(e){ const action = { type: 'change_input_value', value: e.target.value } store.dispatch(action); } handleList(){ return this.state.list.map((item) => { return <li>{item}</li> }) } btnClick(){ const action = { type: 'add_input_value', value: this.state.inputValue } store.dispatch(action); } render() { return ( <Fragment> <div> <input value = {this.state.inputValue} onChange = {this.handleInputChange} /> <button onClick={this.btnClick}>Submit</button> </div> <ul> {this.handleList()} </ul> </Fragment> ); } } export default TodoList;