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

1、問題描述


想經過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,發現:react

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


本來想着既然nextProps能夠拿到數據,用nextPros賦值不就行咯!可是發現後面添加二、三、4....次數據都沒效果了.連componentWillReceiveProps函數都不進去了。可是mapStateToProps的state值卻不斷更新!
state.user的值↓
chrome

2、解決方法


已解決redux

解決方法:infoBox的引用一直是同一個,被react-redux內置的shallow compare給過濾掉了。改變infoBox的引用就好, [...infoBox]或者infoBox.slice()均可以segmentfault

//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數組

相關文章
相關標籤/搜索