简体   繁体   English

使用 redux 和 react 时渲染条件 jsx 的正确方法是什么

[英]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.它被包装在 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.

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.问题是,当父组件挂载时,第二个 requestPending 为 false,因此它呈现 SecondChild 组件。 which gives undefined error since this.props.data is not fetched yet.这给出了未定义的错误,因为 this.props.data 还没有被获取。

What is the appropriate way to render this JSX?渲染这个 JSX 的合适方法是什么?

you can use terinary operator.你可以使用三元运算符。

return (

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

Initial data value could be set to null and初始数据值可以设置为 null 和

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.虽然我建议出现错误 state 并显示错误页面,以防出现 api 错误并且数据根本无法加载。 Showing an infinite loader is bad UX.显示无限加载程序是糟糕的用户体验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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