一、什麼是Reduxjavascript
官方解釋:Redux is a predictable state container for JavaScript apps. 意思就是Redux是js應用的 一種可預測的狀態容器java
二、爲何使用Reduxreact
下面的圖是不使用Redux和使用Redux時 父子組件之間的通訊方式git
沒有使用Redux的狀況,若是兩個組件(非父子關係)之間須要通訊的話,可能須要多箇中間組件爲他們進行消息傳遞,這樣既浪費了資源,代碼也會比較複雜。github
Redux中提出了單一數據源Store 用來存儲狀態數據,全部的組建均可以經過Action修改Store,也能夠從Store中獲取最新狀態。使用了redux就能夠完美解決組建之間的通訊問題。redux
三、怎麼使用Reduxapp
下面是經過Redux實現的TodoList 例子,具體的redux安裝等,移步這裏 redux官網this
store: 建立store,用於存儲state數據spa
//store/index.js import { createStore } from 'redux' import reducer from './reducer'; const store = createStore(reducer); export default store;
reducer:根據傳入的action 向store返回新的statecode
//reducer.js const defaultState = { inputValue: '', list: [] } //reducer 能夠接受state可是不能修改state,須要對state進行深拷貝 export default (state = defaultState, action) => { if (action.type === 'change_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.inputValue = action.value; return newState } if (action.type === 'add_input_value') { const newState = JSON.parse(JSON.stringify(state)); newState.list = [...state.list, state.inputValue] newState.inputValue = ''; return newState; } return state; }
//TodoList.js import React, { Component, Fragment } from 'react'; import store from './store'; class TodoList extends Component { constructor(props){ super(props) console.log(store); this.state = store.getState(); this.handleInputChange = this.handleInputChange.bind(this); this.handleList = this.handleList.bind(this); this.btnClick = this.btnClick.bind(this); this.handleStoreChange = this.handleStoreChange.bind(this); store.subscribe(this.handleStoreChange) } handleStoreChange(){ this.setState(store.getState()); } handleInputChange(e){ const action = { type: 'change_input_value', value: e.target.value } store.dispatch(action); } handleList(){ return this.state.list.map((item) => { return <li>{item}</li> }) } btnClick(){ const action = { type: 'add_input_value', value: this.state.inputValue } store.dispatch(action); } render() { return ( <Fragment> <div> <input value = {this.state.inputValue} onChange = {this.handleInputChange} /> <button onClick={this.btnClick}>提交</button> </div> <ul> {this.handleList()} </ul> </Fragment> ); } } export default TodoList;