在react项目中使用redux
- 安装redux DevTools和在react项目中安装redux(翻墙google应用商店安装)
项目中安装:yarn add redux
或者 npm install redux -S
又或者 cnpm i redux -S
- 创建store
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;

- 创建reduer
const defaultState = { // 默认数据
inputValue: 'focusdroid',
list: [ '北京', '上海', ]
}
// reducer 只能接受state,决不能修改state
export default (state = defaultState, action) => {
console.log(state, action)
if (action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state)); // 深拷贝
newState.inputValue = action.value;
return newState; // 返回给store
}
return state;
}
- 在组件中使用store
import store from '../../store/index'
constructor(props){
super(props);
this.state = store.getState()
this.handleStoreChange = this.handleStoreChange.bind(this)
store.subscribe(this.handleStoreChange)
}
handleStoreChange () { // 让store中的值实时同步
this.setState(store.getState())
}
handleInputChange (e) { // 向store中传递值
const action = {
type:'change_input_value',
value: e.target.value
}
store.dispatch(action)
}