Redux 把所有数据放在 store 里面管理,只需更改 store 里的数据,组件感知到 store 里面的数据变化,再来取数据,从而间接地实现组件之间数据传递的功能。
1.Redux 的工作流程
2.如何使用 redux
(1)首先安装依赖包
yarn add redux
(2)创建 redux 中的 store
// 在 store/index.js 文件下,
import { createStore } from 'redux'
import reducer from './reducer';
const store = createStore(reducer);
export default store
通过 createStore 创建 Store ,将 reducer 的数据存储情况传递给 Store.
(3)如何构建 reducer
// 在 store/reducer.js下,只需返回一个函数
const defaultState = {
inputValue: '',
list: []
} //相当于创建一个空笔记本
// state 表示上一次存储的所有 Store 里面的所有数据,action 表示 这一次提交过来的数据
export default (state, action) => {
return state
}
(4)组件如何连接 Store 来获取数据呢
使用 store.getState() 获取store 中的数据,同时复制到 组件的 state 中去
import store from './store';
constructor(props) {
super(props)
this.state = store.getState()
}
// 组件如何使用呢
<Input value={ this.state.inputValue } />
(5)ActionTypes 的拆分
// actionTypes.js 文件下
export const CHANGE_INPUT_VALUE = 'change_input_value';
(6)使用 actionCreator 统一创建 action
// 在 actionCreators.js 文件下
import { CHANGE_INPUT_VALUE } from './actionTypes'
export const getInputChangeValue = (value) => ({
type: CHANGE_INPUT_VALUE,
value
})
(7)通过 Action 改变 store 里面的数据
import { getInputChangeValue } from './store/actionCreators'
constructor(props) {
this.handleInputChange = this.handleInputChange.bind(this)
}
<Input onChange={this.handleInputChange} />
handleInputChange(e) {
// const action = {
// type: CHANGE_INPUT_VALUE,
// value: e.target.value
// }
const action = getInputChangeValue(e.target.value)
store.dispatch(action)
}
// 将 e.target.value 的值通过 action 改变 store 里面的数据,那么我们怎么创建 action 呢?
// 调用 dispatch 将action 传递给 store
(8)store 获取到action 传递过来的信息,转发给 reducer 进行处理,处理完成后将结果返回 store 中。
import { CHANGE_INPUT_VALUE } from './actionTypes'
const defaultState = {
inputValue: '',
list: []
}
// state 表示上一次存储的数据,action 表示 这一次提交过来的数据
export default (state = defaultState, action) => {
if(action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState
}
return state;
}
注意:reducer 可以接收 state, 但绝不能修改 state,reducer 返回 newState 数据给store,store把新数据替换掉原来的旧数据
(9)store 里面的数据更新了,页面上组件数据并未更新
在组件的constructor 中,添加 store.subscribe 方法。只有store里面数据改变,subscribe 里面的函数自动执行
constructor(props) {
this.handleStoreChange = this.handleStoreChange.bind(this)
store.subscribe(this.handleStoreChange)
}
handleStoreChange() {
this.setState(store.getState());
}
store 数据发生改变,组件使用 setState 来更新数据,通过 store.getState 重新获取数据,这样页面上的数据就和 store 中的数据同步啦。
Redux 设计和使用原则
1.store 是唯一的 【createStore】
2.只有 store 改变自己的内容【reducer 拿到之前的 store 数据,然后一系列处理后将数据返回给了 store,store 拿到新的数据后,把自己的数据更新 】
3.reducer 必须是纯函数【纯函数是给定固定的输入,就一定有固定的输出,而且不会有任何副作用,不能修改 state 中的数据】
Redux 核心 API
1.createStore【创建 store 】
2.store.dispatch【派发action传递给 store】
3.store.getState【可以获取到 store 里面所有的数据】
4.store.subscribe【订阅store的改变,只有store进行改变,这个方法就执行】