簡體   English   中英

REACT + REDUX:在redux狀態更改mapStateToProps更新狀態但視圖不按照新狀態呈現

[英]REACT + REDUX: on redux state change mapStateToProps updating state but view is not rendering as per new state

有我的容器通過redux商店獲得狀態。

我通過這樣的道具將此狀態傳遞給模態框:示例:

render(){
  let {team,id} =this.props.data;
    return(
    <div>
    <ModalExample isOpen={this.state.isOpen} team={team} id={id}
modalClose={this.modalClose.bind(this)} 
handleAddTeam={this.handleAddTeam.bind(this)}/>
        </div>
        )}

它第一次完美地工作...有模式框內的添加按鈕的團隊列表和輸入字段。所以,當我在Modalbox組件內部確定添加方法並更新狀態時,我可以在reduxDevTool甚至狀態中看到狀態更改是mapStateToProps的變化但模態框隊列表沒有更新或說modalbox道具根據狀態變化沒有收到新道具...

即使在這個容器中

render(){
  let {team,id} =this.props.data;
    console.log(this.props.data) **//Here state change is shown**
    console.log(team) **//Here state is not changed**
    return(
    <div>
    <ModalExample isOpen={this.state.isOpen} team={team} id={id}
modalClose={this.modalClose.bind(this)} 
handleAddTeam={this.handleAddTeam.bind(this)}/>
        </div>
        )}

加上我試圖通過這種方式在ModalExample中傳遞道具

team={this.props.data} , team={team} 

但仍然ModalExample視圖沒有更新..

令人困惑 :如果我關閉並打開ModalBox或輸入模態框的內部輸入字段,那么根據我們的新狀態,視圖會發生變化...但我希望根據我們的redux狀態更改即時模態框視圖渲染...

我不確定這是不是最好的方式。 但最近我像這樣解決了我的問題......

實際上,我的redux商店狀態是這樣的

user: {
    data: [
        id: 1,
        key: 'exampleKey',
        name: 'exampleName',
        team: [
            {email: 'one', role: 'one'},
            {email: 'two', role: 'two'}
        ]
    ],
    error: null
}

所以,每當我更新redux store狀態團隊數組時

user: {
    data: [
        id: 1,
        key: 'exampleKey',
        name: 'exampleName',
        team: [
            {email: 'one', role: 'one'},
            {email: 'two', role: 'two'},
            {email: 'three', role: 'three'}
        ]
    ],
    error:null
}

在reduxDevTool中可以很容易地看到改變的redux狀態

並在容器mapStateToProps我處理這樣的狀態,

其中console.log(state.signup.user.data)甚至顯示狀態的變化,但是這不會調用componentWillReceiveProps所以我的視圖沒有呈現......

const mapStateToProps = (state) => {
    return {
        user: state.signup.user.data,
    };
};

我終於通過在mapStateToProps中定義了另一個狀態來解決這個問題

const mapStateToProps = (state) => {
    return {
        user: state.signup.user.data,
        teamMember:state.signup.user.data.team,
    };
};

這會觸發componentWillReceiveProps並立即呈現我的視圖。

在Redux中,狀態改變發生在一些動作和減速器上。

您可以在redux文檔中找到它們動作減速器

你是從商店取得團隊。 如果只是更新團隊對象,則不會觸發任何狀態更改。 它只會改變對象。 要更改狀態,您需要一些可以承載一些有效負載的操作。

例如,“UPDATE_TEAM_NAME”操作將攜帶newName作為其有效負載,而reducer(純函數)將返回新的團隊對象。

除此之外,如果您沒有更新容器中的團隊對象,我建議您在ModelExample組件中獲取團隊對象,而不是將其作為容器中的props傳遞。 它會讓事情變得更清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM