首页 文章

React / Redux:在组件的初始render()调用期间使用Redux存储中的数据

提问于
浏览
0

我想知道如何在初始渲染组件期间在Redux存储中使用数据 . 我正在尝试使用存储在Redux中的auth对象中的MongoDB数据来设置 **** 组件的 name 属性 .

<FontAwesome className="share-icon" name={this.props.auth.primaryAccount} />;

auth.primaryAccount 键将包含一个字符串("google","facebook","github"或"twitter",当此字符串作为组件中的name属性填充时,它将呈现正确的品牌图标 .

如果我有一个通过react-redux Connect() 帮助器同步到Redux存储的父容器 **** ,其中auth对象通过mapStateToProps可用于props,如果 **** component直接放入父组件的render()语句中, this.props.auth.primaryAccount 组件最初呈现时具有空值 . 将console.log(this.props.auth)放入组件的 componentDidMount 方法会产生 null 值,而将console.log(this.props.auth)放入 componentDidUpdate 方法会导致Redux的预期 auth object .

render() {
      return (
       <div className="dashboardContainer">
        <h1>Dashboard</h1>
        <PanelContainer bordered={false} defaultActiveKey={["1"]}>
          <Panel header="PRIMARY ACCOUNT INFORMATION" key="1" showArrow={false}>
            <FontAwesome className="share-icon" name={this.props.auth.primaryAccount} />
          </Panel>
        </PanelContainer>
       </div>
      );
    }

this.props.auth.primaryAccount 的正确值不是' made available from Redux until after the initial component mount/render. I' m,假设这是由于auth操作创建者对MongoDB的查询的异步性质以检索auth对象数据 .

我已经能够通过在辅助函数中使用switch语句来解决这个问题,该函数阻止 **** 组件呈现,直到Redux数据在 this.props (下面)中可用,但是我不想为每个函数编写辅助函数引用Redux中存储的数据的JSX行 . 使用Redux数据进行组件渲染的最佳方法是什么?

renderIcon() {
    switch (this.props.auth) {
      case null:
        return; 
      default:
        return <FontAwesome className="share-icon" name={this.props.auth.primaryAccount} />;
    }
  }

  render() {
    return (
      <div className="dashboardContainer">
        <h1>Dashboard</h1>
        <PanelContainer bordered={false} defaultActiveKey={["1"]}>
          <Panel header="PRIMARY ACCOUNT INFORMATION" key="1" showArrow={false}>
            {this.renderIcon()}
          </Panel>
        </PanelContainer>
      </div>
    );
  }
}

1 回答

  • 0

    查看反应项目中的数据是一种非常常见的模式 . 人们经常使用与switch语句不同的语法 . 他们经常使用这样的条件快捷方式:

    renderIcon() {
        var auth = this.props.auth
        return auth && <FontAwesome className="share-icon" name={auth.primaryAccount} />;
    }
    

    另一个版本是三元运算符:

    renderIcon() {
        var auth = this.props.auth
        return auth ? <FontAwesome className="share-icon" name={auth.primaryAccount} /> : null;
    }
    

相关问题