文章目录
redux三大核心
1 action 触发reducer方法动作
2 reducer
3 store
redux的组件
- Action – 这是一个用来描述发生了什么事情的对象
- Reducer – 这是一个确定状态将如何变化的地方
export default(state, action)=> {
switch(action.type) {
case 'type类型':
return action.payload // 获取发送过来的数据
default:
return 默认值
}
}
- Store – 整个程序的状态/对象树保存在 Store 中
- View – 只显示 Store 提供的数据
redux使用
1 安装redux react-redux
cnpm i redux react-redux --save-dev
2 创建store.js
import {createStore} from 'redux'
import 自定义名字 from 'reducers文件中的对应的reducer'
const store=createStore(自定义名字)
export default store
3 在需要发送数据的组件中 首先引入store 使用store.dispatch({type: '类型', payload: 要发送的数据})
sendData() {
store.dispatch({
type: '类型',
payload: 要发送的数据
})
}
4 创建reducers文件 在文件中编写reducer
export default(state, action)=> {
switch(action.type) {
case 'type类型':
return action.payload // 获取发送过来的数据
default:
return 默认值
}
}
5 在需要接受的组件中 使用store.getState()来获取发送过来的数据
store.subscribe()实时监听store仓库中数据的变化 然后试试更新dom数据
如果react项目中有多个reducer 这个时候 要去创建store 并且需要合并多个reducer
1 需要在store.js文件中引入combineReducers
import {combineReducers} from 'redux'
const reducers=combineReducers({
自定义名字1: reducer1,
自定义名字2: reducer2
...
})
2 需要在store中引入reducers
const store=createStore(reducers)
3 在需要发送数据的组件中 通过store.dispatch({type: 'reducers定义的type类型',payload: 要传递的数据})
4 在需要接收数据的组件中 通过store.getState().reducer1 来获取reducer1中数据