0

考虑这个

  componentDidMount() {
    const { currentUserId, userList } = this.props; 
    //I get these from redux' mapStateToProps function; 
    //these are not passed down as regular props.

    Mousetrap.bind(['shift+right'], () =>
      nextUser(currentUserId, userList)
    );
  }

假设我的列表中有 10 个用户,我们从user 1. 当我启动应用程序时,它会从user 1user 2; 但是,它不会再进一步​​,因为 的值currentUserId将永远是user 1

我怎样才能规避这一点并使论点是动态的,以便更新论点?

编辑:currentUserId&userList通过 Redux 传递给组件

4

2 回答 2

0

如果您希望事情是动态的,请考虑将 currentUserId 复制到构造函数中的状态,并根据需要使用 this.setState({currentUserId: }) 调整状态示例:

constructor(props) {
  super(props);
  this.state = { currentUserId: props.currentUserId };
}

componentDidMount() {
  const { userList } = this.props;
  const { currentUserId } = this.state;

  Mousetrap.bind(['shift+right'], () =>
    nextUser(currentUserId, userList)
  );

}

我不知道你的 nextUser 函数是如何工作的,但如果它返回下一个 userId,你可以这样做:

Mousetrap.bind(['shift+right'], () =>
  this.setState({currentUserId:nextUser(currentUserId, userList)});
);

在 componentDidMount() 中。

于 2019-08-07T13:20:08.990 回答
0

如果需要更新函数,在组件挂载后,需要使用componentDidUpdate来响应组件生命周期中的 prop 变化。

componentDidMount 将被调用一次(当组件变得可见时),您的函数将设置为当前的 prop => onClick 将选择第二个用户。

之后,您的道具会发生变化(currentUserId 现在将成为第二个用户),但您不会更新您的函数。这就是为什么它会卡在第二个用户身上。

要实现您的目标,请将componentDidUpdate 与 componentDidMount结合使用,如下所示:

componentDidUpdate(prevProps) {
    const { currentUserId, userList } = this.props;
    if(prevProps.currentUserId !== currentUserId || prevProps.userList !== userList ) {
        Mousetrap.bind(['shift+right'], () =>
          nextUser(currentUserId, userList)
        );
    }
}

作为替代方案,您还可以从 nextUser 中删除参数,并通过直接在 reducer 中设置 currentUserId 让 action/reducer 处理更新。

希望这可以帮助。快乐编码。

于 2019-08-07T13:39:44.287 回答