【问题标题】:React JSX Component and AwaitReact JSX 组件并等待
【发布时间】:2017-06-27 18:26:35
【问题描述】:

我有一个 async/await 函数,我想使用它的结果在我的 React 本机应用程序中有条件地渲染一个 jsx 组件。

这是一个返回承诺的类方法。该方法已声明异步。

问题是我想用这个结果来有条件地渲染一些jsx。

const hasEdit = await perms.has('/page', 'edit');

return (
      <div>
      { hasEdit &&
        <Button
          icon='pencil'
          text='EDIT'
          onTouchTap={ () => { props.onEdit(); } }
        />
      }
      </div>
    )

这会返回: 必须返回一个有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。

知道我该如何尝试吗?任何事情都将不胜感激。

【问题讨论】:

  • render 不能是异步的。
  • 将该异步调用放入 componentDidMount 并将结果保存到反应状态
  • 如果使用 redux 也一样?将结果推送到反应状态并在渲染中使用它?

标签: reactjs asynchronous promise async-await jsx


【解决方案1】:

建议移动 componentDidMount,使其异步,然后在结果上设置状态,使其在渲染中可用。渲染不能异步。

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多