【问题标题】:mapStateToProps called but not calling componentWillRecieveProps when state has same value当状态具有相同值时,mapStateToProps 被调用但不调用 componentWillRecieveProps
【发布时间】:2019-05-14 21:41:41
【问题描述】:

我有以下减速器:

export default function UserReducer(state = initialState, action){
let nextState;
switch(action.type){
    case USER_RECOVERY_CODE_VALIDATED:
    nextState = {
        ...state,
        recoverycodevalidated : action.payload.recoverycodevalidated
    }
    return nextState;
default:
     return state;
 }
}

我的组件就是这样连接到商店的:

function mapStateToProps(state) {
    console.log("updated");
    return { recoverycodevalidated: state.user.recoverycodevalidated };
 }

export default connect(mapStateToProps)(ResetPasswordCodeScreen)

当道具由于 mapStateToProps 功能而改变时,我将用户重定向到下一个屏幕:

 async componentWillReceiveProps(newProps){
    console.log("updated props");
    if(newProps.recoverycodevalidated){
        this.props.navigation.navigate("ResetPasswordFinal", { userId: this.props.navigation.state.params.userId});
    }
}

问题是当第一次更新状态并且props中设置了recoverycodevalidated的值,第二次如果变量的值是同样,道具不会更新,因为 componentWillRecieveProps 方法没有被触发,即使 mapStateToProps 每次都会被触发.我做错了什么?

【问题讨论】:

  • 您的 componentWillReceiveProps 和您的组件都不会更新......只要您在 mapStateToProps 中收到的 recoverycodevalidated 的值相同

标签: react-native react-redux state react-props


【解决方案1】:

尝试改用 componentDidUpdate

componentDidUpdate(prevProps) { 
     console.log("updated props");
     if (prevProps.recoverycodevalidated) {
        this.props.navigation.navigate("ResetPasswordFinal", { userId: 
        this.props.navigation.state.params.userId});
     }
}

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 2019-11-10
    • 2020-04-08
    • 2021-01-13
    • 2017-11-12
    • 2019-12-12
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多