react-redux的mapStateToProps可取到state值但不会注入props

一、问题描述


想通过react-redux和redux实现react组件之间的通信,reducer、action、store都编写正确,mapDispatchToProps也能正确传值.唯独mapStateToProps的return出现了问题。
//connect参数之一,获取参数 , state为接受的参数
const mapStateToProps = (state) => {
    console.log(state.user);//可持续更新
    return {
        user:state.user;//组件AppContent的this.props.user始终为空
    }
}
AppContent = connect(mapStateToProps)(AppContent)

但是用chrome的react插件查看props状态是存在user数据的(但仅存在第一次添加,后续再添加数据也不会更新props)

所以在生命周期componentWillReceiveProps分别打印了nextProps(接收新的props)和this.props,发现:

console.log(nextProps)  //user[1] 第一次添加数据传入了nextProps
console.log(this.props) //user[0] 依然不存在数据


原本想着既然nextProps可以拿到数据,用nextPros赋值不就行咯!但是发现后面添加2、3、4....次数据都没效果了.连componentWillReceiveProps函数都不进去了。但是mapStateToProps的state值却不断更新!
state.user的值↓

二、解决方法


已解决

解决方法:infoBox的引用一直是同一个,被react-redux内置的shallow compare给过滤掉了。改变infoBox的引用就好, [...infoBox]或者infoBox.slice()都可以

//reducer.js
...
let infoBox = [];

function put_in_infoBox(action){
    infoBox.push(action);   //每新增一条数据就存入infoBox数组中
}

switch(action.type){
        //action.type从action.js中获取,并随着dispatch一起发送
        case 'SEND':
            //处理数据
            put_in_infoBox(action);
            // console.log(infoBox);
            return {
                user:[...infoBox]  //改动infoBox的传值方式!
            }
        
        default:
            return state;
    }
...

但是注意,需要在生命周期componentWillReceiveProps(nextProps)获得更新的props,this.props只会在render渲染的时候更新
具体请参考:https://segmentfault.com/q/1010000015992520

posted @ 2018-08-13 12:12  xiaobe  阅读(5370)  评论(1编辑  收藏  举报