初次学习redux,熟悉ianyigew数字加 1 的小案例
App.js文件
import React from 'react'; import store from './store/index' console.log() class App extends React.Component { constructor(){ super() this.state = { msg : 'HELLO REDUX', num: store.getState().num } this.handleAdd = this.handleAdd.bind(this) store.subscribe(this.upstateNum.bind(this)) } render(){ let {msg,num} = this.state return ( <div className="App"> <h1>{msg}</h1> <h2>{num}</h2> <button className="btn" onClick={this.handleAdd.bind(this)}>加 1 操作</button> </div> ); } handleAdd(){ console.log("加 1 操作") store.dispatch({ type:'addNum' }) } // j坚挺仓库中的数据发生改变后,将指赋给组建的state upstateNum(){ this.setState({ num:store.getState().num }) } } export default App;
store目录下index.js文件
创建一个仓库createS透热(),该函数接受一个参数,参数也是一个函数reducer
import {createStore} from 'redux' import reducer from './reducer' const store = createStore(reducer) export default store
store目录下reducer.js文件
const initState = { num : 10 } const reducer = (state = initState,action)=>{ switch(action.type){ case "addNum": let numState = JSON.parse(JSON.stringify(state)) numState.num++ return numState } return state } export default reducer