ReactJS:子组件的条件渲染取决于是否加载了userData?

时间:2018-03-21 22:43:22

标签: javascript reactjs

所以,我觉得我做错了什么。当用户登录我们的应用程序时,redux将使用服务器的响应进行更新。

许多组件都依赖于此登录状态。

我们将currentUser对象通过props传递给我们所有的子组件。为了确保对象在那里,我们有一个检查:

{isEmpty(currentUser) ? <Loading /> : <PersonalDashboard currentUser={this.props.currentUser} />} 

我们这样做是为了<PersonalDashboard />将拥有所需的数据。否则我们冒险发送一个空对象。

现在,或者,我已经看到使用connect()来检查商店,但这似乎过于繁琐,因为我想让子组件尽可能简单。

这是处理currentUser的正确方法吗?或者是否有另一种方法来检查适当的数据,然后将其与适当的组件呈现相匹配?

示例:

<Routes currentUser={this.props.currentUser} />

const mapStateToProps = ({ session }) => {
 return {
   currentUser: session.user // this comes from our session reducer
 }
}

export default connect(mapStateToProps)(Routes);

<Routes><Routes />之间

<Route path="/personal" component={PersonalDashboard} currentUser={this.props.currentUser} />

<PersonalDashboard /> render() {

{isEmpty(this.props.currentUser) ? <Loading /> : <PersonalAccount currentUser={this.props.currentUser} />} 

1 个答案:

答案 0 :(得分:0)

Redux试图通过对更新发生的方式和时间施加某些限制来使状态变异可预测。其中一个最重要的想法是整个应用程序的状态存储在单个商店中的对象树中。

因此,在您的情况下,您可以考虑使用从商店获取用户登录信息的组件,并使用反应渲染道具与其他组件共享其状态。 更多信息和示例:

https://reactjs.org/docs/render-props.html