redux

话不多说直接上代码

 1 //  store.js
 2 
 3 // 生成store这个对象的
 4 import {createStore} from 'redux'
 5 //creaeStore这个方法的参数必须是一个函数,这个函数我们叫reductor,且有俩个参数 state和action
 6 var store=createStore(function(state=10,action){
 7     console.log(action)
 8     switch(action.type){
 9         case 'ADD':
10             return state+action.payload
11         case 'JIAN':
12             return state-action.payload
13         default:
14             return state
15     }
16     //必须返回一个新的state值
17 })
18 
19 export default store
 1 //  App.js
 2 
 3 import React from 'react';
 4 import './App.css';
 5 import store from './Redux/store'
 6 class App extends React.Component{
 7   constructor(props){
 8     super(props)
 9     this.fn=this.fn.bind(this)
10   }
11   render(){
12     return(
13       <div>
14         <button onClick={this.fn}>+</button>
15         <div>{store.getState()}</div>
16       </div>
17     )
18   }
19   fn(){
20     store.dispatch({type:'ADD',payload:5})
21   }
22 }
23 
24 export default App;
 1 //   index.js
 2 
 3
 4 import React from 'react';
 5 import ReactDOM from 'react-dom';
 6 import './index.css';
 7 import App from './App';
 8 import * as serviceWorker from './serviceWorker';
 9 import store from './Redux/store'
10 ReactDOM.render(<App />, document.getElementById('root'));
11 //store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数。
12 store.subscribe(function(){
13     ReactDOM.render(<App />, document.getElementById('root'));
14 });
15 // If you want your app to work offline and load faster, you can change
16 // unregister() to register() below. Note this comes with some pitfalls.
17 // Learn more about service workers: https://bit.ly/CRA-PWA
18 serviceWorker.unregister();
原文地址:https://www.cnblogs.com/yangzhiqiang/p/11592631.html