【问题标题】:Where to keep active user data on React + Redux client application在 React + Redux 客户端应用程序上保存活动用户数据的位置
【发布时间】:2017-01-16 14:28:39
【问题描述】:

在我的 React + Redux 客户端应用程序中,我需要获取活动用户信息(从 myapp.com/users/me 获取)并将其保存在某个地方,以便我可以从多个组件访问它。

我猜window.activeUser = data 不是最佳做法。但我找不到任何关于这样做的最佳实践的资源。做我想做的事最好的方法是什么?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    您可以将其保存在单独的 reducer 中,然后在组件中使用 connect() 导入状态的多个部分。

    假设您在设置商店时有两个名为 users.jstags.js 的减速器与 combineReducers 结合使用。您只需将函数传递给您的 connect() 调用即可拉出不同的部分。所以使用 es6 + 装饰器:

    const mapStateToProps = state => {
      return {users: state.users, tags: state.tags}
    }
    
    @connect(mapStateToProps)
    export default class MyComponent extends React.Component {
    

    然后在您的render 函数中:

    return (
      <div>
        <p>{this.props.users.activeUsernameOrWhatever}</p>
        <p>{this.props.tags.activeTags.join('|')}</p>
      </div>
    );
    

    所以你不同的 reducer 状态变成了 this.props 上的对象。

    【讨论】:

      【解决方案2】:

      您可以使用 React 的 context、HOC 或全局变量通过上下文使您的数据可用于多个组件

      类似...

      class ParentDataComponent extends React.Component {
         // make data accessible for children
        getChildContext() {
          return { 
            data: "your-fetchet-data"  
          };
        }
      
        render() {
          return < Child />
        }
      }
      
      class Child extends React.Component {
        render() {
          // access data from Parent's context
          return (<div> {this.context.data} </div>); 
        }
      }
      

      【讨论】:

        【解决方案3】:

        创建一个动作创建器并在适当组件的componentWillMount 上调用它,以便它在您的组件安装之前运行,并在动作创建器中获取您需要的数据并将其传递给减速器。在该 reducer 中,您可以在整个应用程序中保留所需的数据。因此,每当您需要数据时,您都可以从 redux 状态中检索它。 this redux 官方网站上的教程涵盖了您需要了解的所有内容。如果您有任何问题,请告诉我。

        【讨论】:

          猜你喜欢
          • 2019-02-08
          • 2016-07-19
          • 1970-01-01
          • 2015-08-21
          • 1970-01-01
          • 1970-01-01
          • 2020-10-24
          • 2012-07-13
          • 2015-05-11
          相关资源
          最近更新 更多