【问题标题】:Render child component only when parent's network call promise is resolved in react仅当父母的网络调用承诺在反应中解决时才渲染子组件
【发布时间】:2018-02-26 09:25:31
【问题描述】:

我不确定它是否是反模式,我在路由级别创建了一个 HOC 并在其中获取用户详细信息,如下所示:

class PrivateRoute extends Component {
  render() {
    const { component : RouteComponent, checkAuth, ...rest } = this.props
    const route = (
      <Route
        {...rest}
        render={(props) => {
          return checkAuth() === true
            ? <RouteComponent {...props} />
            : <Redirect to={{pathname : '/login'}} />
        }}
      />
    )

    return route
  }

  componentWillMount() {
    const { store } = this.props
    const { user } = store.getState()
    const accessToken = getCookie('access_token')

    if (!user.userInfo && accessToken) {
      store.dispatch(getUserDetails(accessToken)) // Setting user details in redux store.
    }
  }
}

const routes = (checkAuth, store) => (
  <div className='app grid'>
    <ConnectedNavbarContainer />
    <div className='col'>
      <Switch>
        <Redirect exact={true} from='/' to='/dashboard' />
        <Route path='/login' component={ConnectedLoginContainer} />
        <PrivateRoute 
          store={store}
          checkAuth={checkAuth} 
          path='/:id/dashboard' 
          component={ConnectedDashboardContainer} 
        />
        <PrivateRoute 
          store={store}
          checkAuth={checkAuth} 
          path='/select-store' 
          component={ConnectedSelectStoreContainer} 
        />
      </Switch>
    </div>
  </div>
)

PrivateRoutecomponentWillMount 函数中观察,我正在获取用户详细信息并将其保存在redux 存储中。现在的问题是 getUserDetails 是异步调用,PrivateRoute 的子组件将进行网络调用以呈现该页面,并且这些网络调用需要用户 ID,该用户 ID 将出现在 getUserDetails 调用的响应中。

现在我希望子组件等到getUserDetails 调用得到解决。我不知道该怎么做。

【问题讨论】:

    标签: javascript reactjs react-router react-redux


    【解决方案1】:

    创建一个将在 redux 存储中设置状态以反映正在检索用户详细信息的操作。这将使子组件能够知道用户详细信息尚未准备好,并显示适当的消息(例如“正在加载...”或“正在初始化...”)。

    检索用户详细信息时,应适当更新上述状态。如果检索用户详细信息失败,则触发另一个将状态设置为错误的操作(并清除“正在加载”状态),以使子进程能够显示错误消息。

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2018-05-18
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多