引入redux npm instll redux --save
1、redux通过store进行数据管理,store更像是一个通信角色。
2、一开始我们需要创建store.js和reducer.js,store用来负责接收通信,读取数据给组件和告诉reducer数据需要发生改变。reducer用来存储组件中的需要的数据和默认值。
store中引入redux的createStore
方法。
// store
import {createStore} from 'redux' //引入createStore方法
const store = createStore()
export default store
reducer 中放置组件需要的数据和默认值,返回一个箭头函数,箭头函数的参数有 state和action,state表示当前存储的数据和值,action表示当数据要发生改变时接收的dispatch
//reducer
const defaultState = { nums:0 }
export default (state, action) => {
return state
}
3、在组件中我们引入store,调用store.getState()
方法并将数据赋值给组件的this.state
import store from './store'
// class
constructor(props){
super(props)
this.state=store.getState()
}
render(){
return <div>{this.state.nums}</div> // 0
}
说完store将reducer中的数据传递给组件,组件接收并显示数据之后,看看组件如何将改变数据的需求告诉store,并由reducer来改变数据,并最后由组件展示改变后的数据。
4、当数据要发生改变,定义一个action对象,action对象有一个type属性来描述当前要发生的动作,并调用store的dispath方法,传入action。
store接收到action后会自动传递给reducer,由reducer根据action的type类型来判断要进行哪些数据操作,并将原数据拷贝之后进行操作,操作完成之后 重新赋值给存储的数据。
当数据发生变化后,在组件中调用store.subscribe()方法,该方法在数据改变后会自动调用。在store.subscribe()方法中传入一个设置当前组件数据state等于新的数据的方法,从而使组件的数据与改变之后的数据保持一致。
// 组件中发起数据改变的动作
// 定义一个action并告知类型
numsClick () {
const action ={
type: 'nums_change'
}
// 调用store的dispatch方法并传入action
store.dispatch(action)
}
store接收到后会将动作自动传递给reducer。reducer根据action类型来进行数据操作
const defaultState={nums:0}
// reducer 不可以直接操作数据
export default(state=defaultState, action) => {
if(action.type==='nums_change'){
const newState=JSON.parse(JSON.stringify(state))
newState.nums++
return newState
}
return state
}
数据变化后,组件中会自动调用store.subscribe()方法。在方法中传递一个组件中可以设置当前组件state数据的方法。并通过stoe.getState()方法将组件的数据与改变后的数据保持一致。
constructor(props){
super(props)
this.numsChange = this.numsChange.bind(this)
store.subscribe(this.numsChange)
}
numsChange(){
this.setState(()=>(store.getState()))
}