export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + action.data
case 'DECREMENT':
return state - action.data
default:
return state
}
}
注意
a. 返回一个新的状态
b. 不要修改原来的状态
store
将 state,action 与 reducer 联系在一起的对象
如何得到此对象?
import {createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
此对象的功能?
getState(): 得到 state
dispatch(action): 分发 action, 触发 reducer 调用, 产生新的 state
subscribe(listener): 注册监听, 当产生了新的 state 时, 自动调用
react-redux
理解
一个 react 插件库
专门用来简化 react 应用中使用 redux
React-Redux 将所有组件分成两大类
UI 组件
a. 只负责 UI 的呈现,不带有任何业务逻辑
b. 通过 props 接收数据(一般数据和函数)
c. 不使用任何 Redux 的 API
d. 一般保存在 components 文件夹下
容器组件
a. 负责管理数据和业务逻辑,不负责 UI 的呈现
b. 使用 Redux 的 API
c. 一般保存在 containers 文件夹下