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

查看:128
本文介绍了在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. Async渲染还不是一个选项。

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

使用React Router v4,渲染道具 Route 组件需要返回有效的React Element或React Elements数组,因此,它不接受函数返回的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 Component,而不是返回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天全站免登陆