redux

話很少說直接上代碼css

 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();
相關文章
相關標籤/搜索