这个问题已经困扰我两天了,在segmentfault上提问过了,但是回答的人很少。我今天又补充了一些描述进去,希望了解的人能帮我看下问题到底出在哪里。这是原文链接
Action 请求来的数据给了reducer,reducer执行后数据没有映射到store上是为什么?
看了代码,感觉用法上好像有些问题,有兴趣可以看看我写的这两个示例:https://github.com/meibin08
https://github.com/meibin08
function mapStateToProps (state, ownProps) {
// 这里的state打印出来的并没有我返回的数据
console.log(state, 'state')
return {
uname: state.uname,
point: state.point,
notice: state.notice
}
}
你的这段代码错了!state是整个store,而你贴出来的其中一个reducer是requestUserInfo;明显你的state.notice…等等路径就错了!你不是在mapStateToProps打印state了吗。直接顺着这个结构找你想要的数据即可!
提示,你写的requestUserInfo这个reducer没有初始化值(state={控对象}),所以即使上面那步:你的state路径正学,你的Header组件在第一次渲染的时候也会报错,因为根本没这个字段!有两个办法:一。在组件里面写三元
state.notice ? 如此这般 : null;(比较low,不推荐);二。在requestUserInfo的初始化state里面写上基础数据!
export const requestUserInfo = (state = {}, action) => {
switch(action.type) {
// 组件中直接使用的dispatch({type: 'HEADER_RECEIVE_USERINFO'})来触发
case 'HEADER_RECEIVE_USERINFO':
return {
...init
}
break
default:
return state
}
}
return {
uname: state.requestUserInfo.uname,
point: state.requestUserInfo.point,
notice: state.requestUserInfo.notice
}
这样写就能拿到,可是我看别人的demo的时候都是直接
return { uname: state.uname, point: state.point, notice: state.notice }
就能拿到数据了,我的为什么还要加一个requestUserInfo才能拿到呢
在reducer里面你return 出来的那个state就是你这里接收的state,结构是一模一样的,所以你跟别人是在reducer里面return state结构不同而已,就目前你给的信息来看