redux学习心得
概念
应用中所有的 state 都以一个对象树的形式储存在一个单一的 store 中。
惟一改变 state 的办法是触发 action,一个描述发生什么的对象。
为了描述 action 如何改变 state 树,你需要编写 reducers。
案例
把一个变量存到全局的store中
action:
export const RECORD_ID = 'record.id'
export function setRecoredId(id) {
return { type: RECORD_ID, id }
}
reducers:
import { combineReducers } from 'redux-immutable'
import * as actions from '../actions'
function recordId(state = null, action) {
switch (action.type) {
case actions.record.RECORD_ID:
return action.id
default:
return state
}
}
export default combineReducers({
recordId
})
reducers里导出的纯函数名可以理解为store(state)里的某个字段
对应页面mapStateToProps函数中的state.get('recode').get('xxx')->xxx字段
reducers 中的action.type对应action取的常量
页面:
setRecordId(id){
const { dispatch } = this.props
dispatch(actions.record.setRecoredId(id))
}
onClick={() => this.setRecordId(item.recordId)}
function mapStateToProps(state, props) {
const record = state.get('record')
const recordId = record.get('recordId')
return { recordId }
}
module.exports = connect(
mapStateToProps
)(Record)
dispatch(actions.record.setRecoredId(id))
点击按钮时:dispatch一个action(派发一个动作,动作的名字叫做setRecoredId)
action只是一个简单的js对象,相当于返回一个名字叫setRecoredId的对象:
setRecoredId:{
type:RECORD_ID,
id
}
type是必须的,理解为这个action的名字。而其他参数可以自定义,比如这里的id
因为要接受传入的参数来构成一个名字叫setRecoredId的对象
所以这里用函数的方式构建:
const RECORD_ID = 'record.id'
function setRecoredId(id){
return {type:RECORD_ID,id}
}
action 构建完后,传到reducers
reducers可以理解为我们放入全局的store中的变量名字:
function recordId(state = [] ,action){
switch(action.type){
case actions.record.RECORD_ID //每次触发dispatch都会有很多action,这里要进行判断,判断传进来的action的type(名字)是不是我们预先给它取的名字 RECORD_ID(record.id)
return action.id //如果是的话,返回action对象中的id字段
default:
return state //如果不是的话,原样返回给别的reducers进行判断
}
}
因为有多个reducers,所以借用react-redux中的combineReducers方法进行合并,最后导出模块
export default combineReducers({
recordId
})
在页面中使用:
在页面的最后部分要调用mapStateToProps方法,表示把state放入props,这样我们就可以用全局的stote了
function mapStateToProps(state, props) {
const record = state.get('record') //得到全局state中的record对象
const recordId = record.get('recordId') //得到record对象中的recordId字段 --> recordId对应reducers中的recordId
return { recordId }
}
module.exports = connect(
mapStateToProps
)(Record)
connect是一个高阶函数,让我们的mapStateToProps挂载到Record组件上
后续
写的很乱,因为我自己也没理解这东西,一直云里雾里。。
能满足目前的开发需求的情况下,就当成笔记先记录下来吧。
等使用多了,有了更多的心得再来重新更新和整理。