【问题标题】:How should a component access data from a store?组件应该如何访问存储中的数据?
【发布时间】:2016-03-03 22:23:09
【问题描述】:

在我的 React 应用程序中,当用户登录时,他们的用户数据设置为 UserStore.currentUser。组件应该如何访问UserStore.currentUser?

似乎有 4 个选项可供组件访问此数据。哪个(如果有)是正确的?

选项 1:将其设置为组件的“状态”

  var ProfilePicture = React.createClass({
    getInitialState: function(){
      return {
        currentUser: UserStore.currentUser
      }
    },
    render: function(){
      return <h1>Hi my name is {this.currentUser.name}</h1>;
    }
  });

选项 2:直接访问商店的属性

var ProfilePicture = React.createClass({
  render: function(){
    return <h1>Hi my name is {UserStore.currentUser.name}</h1>;
  }
});

选项 3:通过 getter 方法访问 store 的属性

var ProfilePicture = React.createClass({
  render: function(){
    return <h1>Hi my name is {UserStore.getCurrentUser().name}</h1>;
  }
});

选项 4:将 currentUser 设置为根组件的状态。作为道具传递给所有其他人

var App = React.createClass({
  getInitialState: function(){
    return { currentUser: UserStore.currentUser };
  },
  render: function(){
    return <div>
      <ThingA />
      <ThingB />
      <ProfilePicture userName={this.state.currentUser.name} />
    </div>;
  }
});

var ProfilePicture = React.createClass({
  render: function(){
    return <h1>Hi my name is {this.props.userName}</h1>;
  }
});

【问题讨论】:

    标签: reactjs refluxjs


    【解决方案1】:

    在这种情况下,我认为这不是一个特别好的主意。如果name 发生变化怎么办?最好将 connect 存储到视图(组件容器)并通过道具将 name 传递给 ProfilePicture。这使您的组件保持解耦。这也使得测试更容易。

    就 React 0.14 而言,我会这样写:

    export default ({name}) => <h1>{`Hi my name is ${name}`}</h1>
    

    基于函数的组件定义只适用于简单的情况。

    【讨论】:

    • 是不是和我这里写的选项3一样?基本上我设置了根应用程序组件的状态,然后将其作为道具传递给需要它的子组件
    【解决方案2】:

    您的商店包含可以将数据返回给您的方法,例如

    getUserinfo:function()
    {
      return currentUser;
    }
    

    现在您可以访问任何您必须调用商店的组件,例如

    var UserStore=require('./UserStore);
    
    var currentuser=UserStore.getUserinfo();
    

    【讨论】:

    • 这不是一个坏主意,因为对 currentUser 的更改不会导致组件重新呈现?
    • 这里没有重新渲染的机会,因为只需将当前用户存储在变量中并在需要的地方返回
    • @DonnyP 一旦用户更改您的整个通量流将被调用,并且更改将自动更新当前用户变量,因此将应用更改
    【解决方案3】:
    mixins: [
        Reflux.listenTo(UserStore,'onSessionChange'),
        ],
    getInitialState() {
        return {
            name: '',
            other: ''
        };
    },
    componentDidMount() {
        UserActions.getUserInfo();
    },
    onSessionChange(userInfo) {
        this.setState({
            name: userInfo.name,
            other: userInfo.other
        })
    },
    

    由于您使用的是回流js,我认为最好听听组件中的数据变化。

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 2020-12-03
      • 2019-09-25
      • 1970-01-01
      • 2012-11-12
      • 2017-02-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多