簡體   English   中英

使用 redux 和 react 時渲染條件 jsx 的正確方法是什么

[英]What is correct way to render conditional jsx when using redux with react

這是組件代碼。 它被包裝在 connect function 中,並適當地設置了 mapStateToProps 和 mapDispatchToProps。

   //Parent component
    componentDidMount() 
    {this.props.dispatchAction()}//dispatches action which sets requestPending state in redux to true and fetches data. when the data is fetched it sets requestPending to false again.

然后在父組件的渲染方法中。

if (this.props.requestPending) return <Loading />; 
if (!this.props.requestPending) return <SecondChild {...this.props.data} />; 

問題是,當父組件掛載時,第二個 requestPending 為 false,因此它呈現 SecondChild 組件。 這給出了未定義的錯誤,因為 this.props.data 還沒有被獲取。

渲染這個 JSX 的合適方法是什么?

你可以使用三元運算符。

return (

   this.props.requestPending ? <Loading /> : <SecondChild {...this.props.data} />
)

初始數據值可以設置為 null 和

render() {
  const { requestPending, data } = props;

  if(requestPending || !data) {
    return  <Loading />;
  }

  return  <SecondChild {...this.props.data} />;
}

雖然我建議出現錯誤 state 並顯示錯誤頁面,以防出現 api 錯誤並且數據根本無法加載。 顯示無限加載程序是糟糕的用戶體驗。

暫無
暫無

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

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