在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ React-redux中mapStateToProps無(wú)法注入props?

React-redux中mapStateToProps無(wú)法注入props?

問(wèn)題描述

想通過(guò)react-redux和redux實(shí)現(xiàn)react組件之間的通信,reducer、action、store都編寫(xiě)正確,mapDispatchToProps也能正確傳值.唯獨(dú)mapStateToProps的功能不正確,其里面的state值也會(huì)根據(jù)傳值改變,但是render里打印this.props只有第一次的值,后面再傳入值都不再渲染到props

截圖

  1. 輸入第一次內(nèi)容: Props有內(nèi)容
    clipboard.png
  2. 輸入第二次內(nèi)容: Props內(nèi)容依然保持第一條不變,并且生命周期、Render均不進(jìn)入
    clipboard.png
    Props也只有最初的一條
    clipboard.png

相關(guān)代碼

//mapStateToProps(接收數(shù)據(jù))
function mapStateToProps(state){
    console.log(state.user);
    return {
        users:state.user
    }
}

AppContent = connect(mapStateToProps)(AppContent)

export default AppContent;
//reducer.js
let infoBox = [];

function put_in_infoBox(action){
    infoBox.push(action);   //每新增一條數(shù)據(jù)就存入infoBox數(shù)組中
}

function sendMsg(state,action){
    if(!state){
        //如果無(wú)數(shù)據(jù)
        return {
            user:{}
        }
    }

    switch(action.type){
        //action.type從action.js中獲取,并隨著dispatch一起發(fā)送
        case 'SEND':
            //處理數(shù)據(jù)
            put_in_infoBox(action);
            console.log(infoBox);
            return {
                user:infoBox
            }
        
        default:
            return state;
    }
}

export default sendMsg
//store.js
//創(chuàng)建中轉(zhuǎn)數(shù)據(jù)存儲(chǔ)庫(kù)
import reducer from './reducer'

import { createStore } from 'redux' 

const store = createStore(
    reducer,
)

export default store
export const sendMsgAction = ({name,message}) => ({
    type:'SEND',
    name,
    message
})
//mapDispatchToProps(發(fā)送數(shù)據(jù))

const mapDispatchToProps = (dispatch)  => {
    return {
        //傳值
        onSendMsg({name,message}){
            // console.log(message);
            dispatch(sendMsgAction({name,message}));
        },

    }
}

AppFoot = connect(
    null,
    mapDispatchToProps
)(AppFoot)

export default AppFoot;

效果

  1. 應(yīng)有效果:this.props是mapStateToProps每次更改state后的值
  2. 實(shí)際效果:this.props目前只顯示第一組傳入數(shù)據(jù)
回答
編輯回答
厭遇

infoBox的引用一直是同一個(gè),被react-redux內(nèi)置的shallow compare給過(guò)濾掉了。

改變infoBox的引用就好, [...infoBox]或者infoBox.slice()都可以

2017年11月2日 13:59
編輯回答
神經(jīng)質(zhì)

reducer 給 createStore() 之前用 combineReducers() 處理一下你的 reducer

2017年7月23日 09:22