如果我們想使用redux,第一步需要通過
yarn add redux
來安裝redux
安裝成功后就需要去創建一個store,怎么創建呢,非常的簡單,在src下面創建一個文件夾,這個文件夾名字就叫做store,里面有個index.js,reducer.js
index.js
import { createStore } from 'redux'; // 創建store的時候需要把筆記本傳遞給store import reducer from './reducer'; /** * window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() * 這句話的意思是如果頁面上安裝了redux devtools這個擴展,那么就在頁面上使用這個工具 * 有了這個工具之后,再去做redux的調試就非常方便了 */ const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store;
reducer.js
// 創建筆記本,筆記本里面放了很多圖書館的操作,存儲數據情況 /** * state里面放的就是整個圖書館里面的圖書信息,對於redux就是整個存儲的數據 * action * todolist里面創建了action這句話,到那時store並不知到怎么去改變,需要把數據傳給筆記本,讓筆記本告訴我怎么處理, * 很好的一件事情,store會自動的去傳遞這件事情 * 那么這個時候就知道reducer里面這個state是什么,上一次存儲的state,action是什么,傳遞過來的那句鵠 */ const defaultState = { inputValue: '123', list: [1,2] }; /** * reducer 可以接收state,但是絕不能修改state,所以返回給store,store去自動替換 * store發生改變,但頁面並沒有改變,需要在頁面上去接收,怎么接收 * 通過 store.subscribe 接收 */ export default (state = defaultState, action)=> { if( action.type === 'change_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.inputValue = action.value; return newState; // return給了store } if (action.type === 'add_todo_item') { const newState = JSON.parse(JSON.stringify(state)); newState.list.push(newState.inputValue); newState.inputValue = ''; return newState; } console.log(state, action) return state; }
todolist
import React, {Component} from 'react'; import { Input, Button, List } from 'antd'; import 'antd/dist/antd.css'; import store from './store/index' class TodoList extends Component{ constructor(props){ super(props); this.state = store.getState(); this.handleInputChange = this.handleInputChange.bind(this); this.handleStoreChange = this.handleStoreChange.bind(this); this.handleBtnClick = this.handleBtnClick.bind(this); store.subscribe(this.handleStoreChange); } render() { return ( <div style={{margin:'10px'}}> <Input placeholder="todo info" value={this.state.inputValue} onChange = {this.handleInputChange} style={{width:'300px', marginRight:'10px'}} /> <Button type="primary" onClick={this.handleBtnClick}>提交</Button> <List style={{width:'300px', marginTop:'10px'}} size="small" bordered dataSource={this.state.list} renderItem={item => (<List.Item>{item}</List.Item>)} /> </div> ) } handleInputChange(e){ // 去改變store里面的內容,首先要創建一句話,告訴store const action = { type: 'change_input_value', value: e.target.value } // 那么怎么把這句話傳給store呢,store里面有個方法叫做dispatch,這個方法就可以把這句話傳給store store.dispatch(action); } handleStoreChange() { /** * 當我感知到數據發生變化的時候,我去調用store.getState()從store里面重新去取數據 * 然后調用setState替換掉當前組件里面的數據 */ this.setState(store.getState()) } handleBtnClick() { // 首先數據改變了,要去修改store里面的內容,首先要創建一個action const action = { type: 'add_todo_item' } // action創建好了,要傳遞過去,store會自動轉發給reducer store.dispatch(action); } } export default TodoList;