【问题标题】:How prevent double rendering in react based on asynchronous call in componentDidMount?如何防止基于componentDidMount中的异步调用的反应中的双重渲染?
【发布时间】:2019-04-16 19:37:23
【问题描述】:

我有一个父组件和两个子组件。一场成功一场失败 我需要在页面加载时基于异步调用显示这些组件。 所以我在页面componentDidMount上做了异步调用。但这会导致双重渲染。

constructor(props) {
  super(props)
  this.state = {
    showSuccessPage: false
  }
}

componentDidMount() {
  ActiveAccount.fetchActiveAccount(this.handleSuccess, this.handleFailure)
}

handleSuccess() {
  this.setState({
    showSuccessPage: true
  )}
}

...

render() {
  ...
  return (
    {showSuccessPage && <SuccessPage />}
    {!showSuccessPage && <FailurePage />}
  )
}

它总是先渲染失败页面,然后更新渲染成功页面。如何防止双重渲染?

【问题讨论】:

  • 您可以将渲染逻辑缩短为showSuccessPage ? &lt;SuccessPage /&gt; : &lt;FailurePage /&gt;

标签: reactjs asynchronous call mount


【解决方案1】:

为了按预期渲染组件,二进制状态是不够的。这可以用具有 3 个值的单一状态属性 showSuccessPage 表示,undefinedtruefalse。或具有 2 个状态属性:

  ...
  {state.accountFetched && (
    state.accountFetchSuccess ? <SuccessPage/> : <FailurePage/>
  )}
  ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2023-03-04
    • 2022-01-23
    • 2021-08-29
    • 2021-09-26
    • 2020-12-16
    • 2022-11-07
    相关资源
    最近更新 更多