目录结构
| src
-| index.js
-| App.js
-| store.js
-| reducer.js
-| actionCreator.js
-| actionTypes.js
-| Ui.js
安装redux
-
在store.js中引入redux中的createStore、combineReducers
createStore: 创建store,并传入reducer
combineReducers: 将多条reducer合并 -
创建reducer.js,处理state
const defaultState = { input: '' } export default (state = defaultState, action) => { switch (action.type) { case actionTypes.CHANGE_INPUT: return { ...state, input: action.value } default: return state } } -
创建actionCreator.js,定义action方法
export const changeInput = (value) => ({ type: actionTypes.CHANGE_INPUT, value: value }) -
在App.js中事件触发,dispatch调用action,改变state,更新store
-
在App.js中store.subscribe()订阅store变化,更新store,更新所有组件view
总结


本文详细介绍了如何在React项目中使用Redux进行状态管理。从目录结构搭建开始,逐步讲解了store、reducer、actionCreator的创建过程。通过具体代码示例,展示了如何在组件中触发事件并更新state,实现store的订阅与组件视图的更新。
600

被折叠的 条评论
为什么被折叠?



