首页 > 解决方案 > ComponentDidMount 触发两次

问题描述

我在两条路线之间导航时遇到问题。我的情况如下:

我有 2 条路线:Route1Route2- 都是兄弟姐妹。

假设我在 Route1,我可以从那里导航到 Route2,并传递参数(总是)。我调查了以下方式快速导航时的错误行为:

Route1 -> Route2 (param: 1) -> Route 1 -> Route 2 (param: 2)

我已将控制台日志放入其中Route2 componentDidMount以查看以下输出:

const { navigation } = this.props;
console.log(navigation.state.params.param);

令我惊讶的是,如果我快速导航,上述场景的输出将是:

1 
1 
2

虽然预期的行为是:

1
2

知道发生了什么吗?

标签: react-nativereact-navigation

解决方案


当您从 Route2 导航到 Route1 时,它是从右侧进入还是从左侧进入?它可能会安装两次,因为 react-navigation 很有趣:P

您也可能按得太快了。在这种情况下,请在第一次单击后将按钮禁用几百毫秒。

class Button extends React.Component {
  onPress = () => {
    if (this.props.disabled) return;
    if (this.canPress) {
      this.canPress = false;
      this.props.onPress();
      setTimeout(() => { this.canPress = true; }, this.props.pressTimeout || 500);
    }
  }
....

推荐阅读