【问题标题】:What is correct way to render conditional jsx when using redux with react使用redux和react时渲染条件jsx的正确方法是什么
【发布时间】:2021-02-07 21:06:59
【问题描述】:

这是组件代码。 它被包裹在连接函数中,并适当设置了 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.

然后在父组件的render方法中。

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

问题在于,当父组件挂载时,分秒 requestPending 为 false,因此它呈现 SecondChild 组件。这给出了未定义的错误,因为 this.props.data 尚未获取。

渲染这个 JSX 的适当方式是什么?

【问题讨论】:

  • 你应该从你的代码中提供更多。

标签: javascript reactjs


【解决方案1】:

初始数据值可以设置为null和

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

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

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

虽然我建议有一个错误状态并显示一个错误页面,以防出现 api 错误并且数据根本不会加载。显示无限加载器是糟糕的用户体验。

【讨论】:

  • 如果我必须加载页面一次,这将起作用。但下次如果使用反应路由器导航到页面。数据仍将处于 redux 状态。我还需要它持久化,所以不能在卸载时将数据清空。
  • 数据不会为空,如果它已经被提取并且在存储中。
【解决方案2】:

你可以使用三元运算符。

return (

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

【讨论】:

  • 但是当组件第一次挂载时,它仍然会在那个瞬间渲染 SecondChild,从而导致错误。
猜你喜欢
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多