在 React Router v4 中渲染异步组件 [英] Render async component in React Router v4

查看:20
本文介绍了在 React Router v4 中渲染异步组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据组件从如下所示的 api 接收到的负载来呈现组件

I want to render a component based on the payload it receives from an api like below

<Route path="/foo/bar" render={() => {
  return (get('/some/api').then((res) => {
    return <Baz data={res.data} />
          }).catch((err) => console.log))
        }} />

但我收到错误:

Objects are not valid as a React child (found: [object Promise]). If you 
meant to render a collection of children, use an array instead. 

即使我将 Baz 包裹在 []

推荐答案

不幸的是,最新版本的 React - 16.异步渲染还不是一个选项.

unfortunately with the latest version of React - 16. Async rendering is not an option yet.

在 React Router v4 中,Route 组件的 render 道具期望返回一个有效的 React 元素或 React 元素数组,因此,它不接受Promise 对象从您的函数返回.

With React Router v4, the render props of Route component expects a valid React Element or array of React Elements to be returned, therefore, it doesn't accept the Promise object return from your function.

然而,使用当前版本的 React 和 React Router 来实现你想要的并不是不可能的.你只需要稍微调整你的代码.您的 render 应该返回一个 React 组件,而不是返回 Promise,然后您可以根据该组件内的异步值进行条件渲染.

However, it's not impossible to achieve what you want with the current version of React and React Router. You just need to tweak your code a little bit. Instead of returning a Promise, your render should return a React Component, then you can do conditional rendering based on async value inside that component.

它应该看起来像:

<Route path="/foo/bar" render={BazWrapper} />


class BazWrapper extends React.Component {

    // Do asynchronous action here
    async componentDidMount() {
       try {
          const apiValue = await get('/some/api');
          this.setState({ apiValue })
       } catch(err) {
          // error handling
       }
    }

    render() {
        const { apiValue } = this.state; 
        return <Baz data={apiValue} />;
    }

}

通过在异步调用完成后调用 setState,你让 React Component 知道数据已经准备好,它应该重新渲染组件.

By calling setState after the asynchronous call finish, you let React Component know that the data is ready and it's should re-render the component.

这篇关于在 React Router v4 中渲染异步组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆