【问题标题】:How can I access React/Redux current user outside of the render method?如何在渲染方法之外访问 React/Redux 当前用户?
【发布时间】:2016-12-14 20:06:19
【问题描述】:

我有一个 React/Redux/Firebase 应用程序,我需要在渲染方法之前检查当前用户的用户名,以便知道是否需要去数据库并检索其他用户。

但是,由于某种原因我不清楚,我无法在渲染方法之外访问this.props.currentUser。它返回 null。

基本上,我想在函数内部访问它。我的代码如下所示:

 componentDidMount() {
  var userURL = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');

  if(this.props.currentUser.username !== userURL) {
    this.getDbUser(userURL);
    console.log(userURL);
  }
}

我收到一个错误

Cannot read property username of null

我可以在render() 中正常访问该数据。任何想法如何解决这个问题都会很棒。谢谢!

【问题讨论】:

  • 可能是您的渲染方法运行了两次,在第二次运行时,用户被定义。这就是它在渲染中起作用的原因
  • 谢谢,渲染实际上运行了两次,不知道为什么。我在构造函数中调用了一个 fetchUser 方法,所以它不应该是可用的吗?
  • 如果它是异步的则不是

标签: reactjs firebase redux


【解决方案1】:

编辑:实际上 - ComponentDidMount 在您的异步“获取”返回之前运行,因此 currentUser 将是 null。尝试将 ComponentDidMount 更改为 ComponentWillReceiveProps(nextProps) 并将代码中的 'this.props' 替换为 'next.props'。

ComponentWillReceiveProps 中的所有内容都将在使用“获取”用户更新您的道具后运行。例如:

 componentWillReceiveProps(nextProps) {
  var userURL = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');

  if(nextProps.currentUser && nextProps.currentUser.username !== userURL) {
    this.getDbUser(userURL);
    console.log(userURL);
  }
}

上面的代码在 IF 中也包含了&&,所以如果 currentUser 是null 就不会出错。

文档:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 2018-09-23
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多