💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] `npm i redux -s`或`yarn add redux` ~~~ 在chrome商店中安装redux ~~~ 目录结构 ![](https://box.kancloud.cn/a44f86985ab1910fa28f78035f9d34e6_207x294.png) ## 1.定义store管理哪些数据 ``` import {createStore} from 'redux'; ``` ## 2.定义reducer放置数据 ``` var defaultState={ inputValue:"hello world", list:[] } export default (state=defaultState,action)=>{ if(action.type==="inputChange"){ var newState = {...state}; newState.inputValue = action.value; return newState; } return state; } ``` ## 3.将reducer中的数据和store通信 ``` import reducer from './reducer'; const store = createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store; ``` ## 4.在app.js中用使用store中的数据 ``` import store from './store/index.js'; class App extends Component { constructor(props){ super(props); this.state = store.getState() } } ``` ## 5.事件派发action给store ``` handleChange=(event)=>{ var action ={ type:"inputChange", value:event.target.value } store.dispatch(action); } ``` ## 6.在reducer中改变state ``` var defaultState={ inputValue:"hello world", list:[] } export default (state=defaultState,action)=>{ if(action.type==="inputChange"){ var newState = {...state}; newState.inputValue = action.value; return newState; } return state; } ``` ## 7.组件订阅store的改变 ``` constructor(props){ super(props); this.state = store.getState() /* 只要store的状态发生改变的时候就会触发 */ store.subscribe(this.handleStoreChane) } handleStoreChane=()=>{ this.setState(store.getState()) } } ```