【问题标题】:How to call a function in componentDidMount dynamically?如何动态调用componentDidMount中的函数?
【发布时间】:2023-04-06 18:18:01
【问题描述】:

考虑一下

  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 1 变为user 2但是,由于currentUserId 的值将永远是user 1,因此不会再进一步​​了。

我怎样才能避免这种情况并让参数是动态的,以便更新参数?

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

【问题讨论】:

  • 尝试将您的currentUserId 存储在state 中,而不是props
  • 如何保存 currentUserId 和 userList ?在 Redux 中还是在父级中? nextUser 是做什么的?
  • 对不起,那一定是混淆了!我将它们存储在 Redux 中!
  • @Domino987 nextUser 将用户更新为下一个活动用户(来自列表)

标签: javascript reactjs binding function-binding


【解决方案1】:

如果您希望事情是动态的,请考虑将 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()中。

【讨论】:

  • 我认为这行不通,因为他可能在 redux 中同时需要它们。
【解决方案2】:

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

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

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

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

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 处理更新。

希望这会有所帮助。 编码愉快。

【讨论】:

  • As an alternative, you could also remove the parameters from nextUser and let the action/reducer handle the update by setting the currentUserId within the reducer directly. - 我想这样做,但它似乎是一种反模式?我已经在这里stackoverflow.com/questions/57376470/… 提出了这个问题,但没有收到正确的答案。一条评论说动作应该是纯粹的 - 但我不知道,只知道减速器必须是。
  • 是的,行动应该是纯粹的,但每条规则都应该谨慎行事,在我看来,这是一个用例,您可以在减速器中执行此操作。但我确信有人不同意我的观点。如果您严格希望保持操作纯粹,请使用 componentDidUpdate 方法。如果您想让它保持轻松和易于维护,请使用 reducer 方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 2019-01-23
  • 2020-11-26
  • 2019-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多