1、安裝redux yarn add redux
2、創建store
- 列表項目創建store文件夾
- 文件夾下創建index.js
- index.js
import { createStore } from 'redux';
const store = createStore();
export default store;
3、創建reducer.js
const defaultState = {
inputValue:""
}
export default (state = defaultState,action) => { return state }
5、store中如何獲取reducer的數據,及改變
//index.js做如下修改
import { createStore } from 'redux';
import reducer from './reducer'
const store = createStore(reducer);
export default store;
6、組件中如何獲取store數據
- 組件中引入store文件下的index.js
- 在constructor中 this.state = store.getState();
7、如何改變store的數據
- 創建action const action = { type:'input_action',val:val};
- store.dispatch(action) -> store ->reducer改變store數據 返回一個新的state數據
8、如何監聽 store的數據改變,刷新dom
- 組件中的constructor使用 store.subscribe(this.listener.bind(this));
- listener () { this.setState(store.getState())};