[英]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.