企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Redux教程 ## 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()) } } ~~~