简体   繁体   中英

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

Here is the component code. it is wrapped in connect function with mapStateToProps and mapDispatchToProps set appropriately.

   //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.

then in render method of parent component.

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

the problem is that when parent component mounts, for split second requestPending is false so it renders SecondChild component. which gives undefined error since this.props.data is not fetched yet.

What is the appropriate way to render this JSX?

you can use terinary operator.

return (

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

Initial data value could be set to null and

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

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

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

Though I would recommend having an error state and showing an error page incase there is an api error and data doesn't load at all. Showing an infinite loader is bad UX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM