【问题标题】:componentDidMount fire twice when navigate using react router使用反应路由器导航时 componentDidMount 触发两次
【发布时间】:2018-11-06 04:33:27
【问题描述】:

我在 componentDidMount 中有一个异步调用,当我刷新页面时,它按预期工作,但是当我从其他地方导航进入页面时,它调用了两次我的异步操作,我不知道为什么,下面是我的代码.

export default class EditorWrap extends Component {
  constructor(props) {
    super(props)

    this.state = {
      loadedS3Credential: false
    }

    this.config = {
      placeholderText: 'edit here'
    }
  }

  async componentDidMount() {
    if (!this.state.loadedS3Credential) {

      console.log('fire')

      const imageUploadToS3 = await axios('/signS3').then(resp => resp.data)
      if (imageUploadToS3) {
        this.config = {
          ...this.config,
          imageUploadToS3
        }

        this.setState({
          loadedS3Credential: true
        })
      }
    }
  }

  render() {
    if (!this.state.loadedS3Credential) return null

    return (
      <EditorBody
        config={this.config}
      />
    )
  }
}

【问题讨论】:

  • 请提供你渲染&lt; EditorWrap ../&gt;组件的代码,问题可能就在那里

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

您正在使用异步方法,它将在组件中调用两次或多次。只需删除它,您的问题就会得到解决。

编码愉快!

【讨论】:

  • 跟异步一点关系都没有,componentDidMount应该被调用一次
猜你喜欢
  • 1970-01-01
  • 2016-04-10
  • 2020-12-31
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 2020-10-27
  • 1970-01-01
相关资源
最近更新 更多