簡體   English   中英

React router 4:如何在Route的render方法中等待promise的解析?

[英]React router 4: How to wait for a promise to resolve, inside render method of Route?

我正在嘗試實現功能,其中每個Route將首先等待一些ajax承諾解決,然后才會呈現路由。 我看到onEnter不再存在,所以我正在嘗試渲染方法。

我的路線定義如下:

{cmsRoutes.map((route, idx) => {
              console.log(route.resolve)
              return route.component ? (<Route  key={idx} path={route.path} exact={route.exact} name={route.name} render={props =>{
               route.resolve()
               .then(({data})=>{
                 console.log(data)
                  return (
                <route.component {...props} />
              )
                }) 

              } } />)
                : (null);
            },
            )}

正如您所看到的,它只是迭代某個數組,它保存每個路由的數據。 路由對象的一個​​字段是“resolve”,它指向一個返回promise的函數。 像這個:

const resolvemanageContactApplications = ()=> {
  return ajax('/contact')
};

執行此操作時,我收到以下錯誤:

路線(...):渲染沒有返回任何內容。 這通常意味着缺少return語句。 或者,為了不渲染,返回null。

這當然會發生,因為在執行ajax時,路由沒有返回任何內容。 問題是:如何讓React路由器4等待承諾解析? 必須有某種方式。 我記得AngaulrJS UI-Router實際上有一些“解決”api。

你需要另一種方法。

如果你的ajax完成了,你應該使用一個狀態來存儲。 然后,為了渲染路徑,如果未完成ajax,則可以不渲染任何內容(null或... loading),並使用ajax的結果渲染實際組件或任何您想要的內容。

我可以看到你正在基於一組數據生成路由,為了實現這一點,我將創建一個Component來包裝數據加載條件。 它可以作為道具接收:

  • 決心(ajax功能)
  • 要渲染的組件

在componentDidMount和componentDidUpdate上執行ajax調用並將state.waitingResolve設置為true,並在resolve的state.waitingResolve .then()上,將state.waitingResolve設置為false,並將返回的數據也存儲到狀態。

在渲染上,您檢查state.waitingResolve ,並渲染null(或... loading)或渲染您從props收到的組件。

它可能看起來很復雜但值得。

您可以創建一些異步組件包裝器,如:

class AsyncComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      Component: null
    };
  }

  componentDidMount() {
    const { componentPromise } = this.props;
    componentPromise.then(component => this.setState({
      Component: component
    }));
  }

  render() {
    const { Component } = this.state;

    if (!Component) {
      return null; // You can return some spinner here
    }

    return (
      <Component {...this.props} />
    );
  }
}

並在路由器中使用它:

<Route
  key={idx}
  path={route.path}
  exact={route.exact}
  name={route.name}
  render={props => (
    <AsyncComponent componentPromise={route.resolve} {...props} />
  )}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM