1.调试redux使用redux devtool(google商城安装)
2.在store/index.js文件配置store的第二个参数
import { createStore,compose } from 'redux';
import reducer from './reducer';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers());
export default store;
3.在组件中引入store
import store from './store';
4.提交action给store
handleBtnClick() {
const action = {
type:'add_todo_item'
};
store.dispatch(action);
}
5.store接收到action后,把信息传递给reducers进行处理
下面这段处理信息写在store文件夹下的reducers.js里
reducer可以接受state,但不可以修改state,所以每次都是拷贝一个state,然后修改新的state,最后把新state返回给store
//reducer可以接受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_todo_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = '';
console.log(newState);
//reducer要return newState
return newState;
}
return state;
}