REACT + REDUX:在redux状态更改mapStateToProps更新状态但视图不按照新状态呈现

问题描述 投票:3回答:2

有我的容器通过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状态更改即时模态框视图渲染...

javascript reactjs object redux state
2个回答
1
投票

我不确定这是不是最好的方式。但最近我像这样解决了我的问题......

实际上,我的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并立即呈现我的视图。


0
投票

在Redux中,状态改变发生在一些动作和减速器上。

你可以在redux文档中找到它们ActionsReducers

你是从商店取得团队。如果只是更新团队对象,则不会触发任何状态更改。它只会改变对象。要更改状态,您需要一些可以承载一些有效负载的操作。

例如,“UPDATE_TEAM_NAME”操作将携带newName作为其有效负载,而reducer(纯函数)将返回新的团队对象。

除此之外,如果您没有更新容器中的团队对象,我建议您在ModelExample组件中获取团队对象,而不是将其作为容器中的props传递。它会让事情变得更清晰。

© www.soinside.com 2019 - 2024. All rights reserved.