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

时间:2017-04-25 05:23:45

标签: javascript reactjs object redux 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>
        )}

第一次完美地工作...... 模块框内有添加按钮的团队列表和输入字段.so, 当我在 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状态变化即时模态框视图渲染...

2 个答案:

答案 0 :(得分: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并立即呈现我的观点。

答案 1 :(得分:0)

在Redux中,状态更改会发生在某些操作和缩减器上。

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

你正从商店取货。如果只是更新团队对象,则不会触发任何状态更改。它只会改变对象。要改变状态,你需要一些能带来一些有效载荷的动作。

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

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