1.安装redux
npm install redux
2.store的创建 (src/store/index.js)
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
(src/store/reducer.js) 管理store状态的变化
const defaultState = {
inputValue: ' ',
list: [ ]
}
export default (state = defaultState, action) => {
return state;
}
在需要的组件中引入store
import store from './store/index'
输出store
store.getState()
赋值给this.state
this.state = store.getState()
修改输入框数据。
handleInputValue(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action)
}
(src/store/reducer) reducer不能修改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;
}
return state;
}
页面监听数据
this.handleStoreChange = this.handleStoreChange.bind(this);
store.subscribe(this.handleStoreChange);
handleStoreChange() {
this.setState(store.getState())
}