Reactjs 组件应该如何从存储访问数据?

Reactjs 组件应该如何从存储访问数据?,reactjs,refluxjs,Reactjs,Refluxjs,在我的React应用程序中,当用户登录时,他们的用户数据设置为UserStore.currentUser。组件应该如何访问UserStore.currentUser 组件似乎有4个选项可以访问此数据。哪一个(如果有的话)是正确的 选项1:将其设置为组件的“状态” var ProfilePicture=React.createClass({ getInitialState:函数(){ 返回{ currentUser:UserStore.currentUser } }, render:functio

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

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

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

var ProfilePicture=React.createClass({
getInitialState:函数(){
返回{
currentUser:UserStore.currentUser
}
},
render:function(){
return Hi我的名字是{this.currentUser.name};
}
});
选项2:直接访问商店的财产

var ProfilePicture = React.createClass({
  render: function(){
    return <h1>Hi my name is {UserStore.currentUser.name}</h1>;
  }
});
var ProfilePicture=React.createClass({
render:function(){
return Hi我的名字是{UserStore.currentUser.name};
}
});
选项3:通过getter方法访问存储的属性

var ProfilePicture = React.createClass({
  render: function(){
    return <h1>Hi my name is {UserStore.getCurrentUser().name}</h1>;
  }
});
var ProfilePicture=React.createClass({
render:function(){
return Hi我的名字是{UserStore.getCurrentUser().name};
}
});
选项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>;
  }
});
var-App=React.createClass({
getInitialState:函数(){
返回{currentUser:UserStore.currentUser};
},
render:function(){
返回
;
}
});
var ProfilePicture=React.createClass({
render:function(){
return Hi我的名字是{this.props.userName};
}
});

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

关于React 0.14,我将写下如下内容:

export default ({name}) => <h1>{`Hi my name is ${name}`}</h1>
导出默认值({name})=>{`Hi我的名字是${name}`}

基于函数的组件定义仅在简单的情况下有效。

您的存储包含可以像这样返回数据的方法

getUserinfo:function()
{
  return currentUser;
}
现在,您可以访问任何组件,只需像这样调用存储即可

var UserStore=require('./UserStore);

var currentuser=UserStore.getUserinfo();

当您使用refluxjs时,我认为最好听听组件中的数据更改。

这与我在这里写的选项3类似吗?基本上我设置了根应用程序组件的状态,然后将其作为道具传递给需要它的子组件这不是一个坏主意,因为对currentUser的更改不会导致组件重新运行吗?这里没有重新运行的机会,因为只需将当前用户存储在变量中并返回到它所在的位置required@DonnyP一旦用户改变,整个通量流将被调用,并且改变了将自动更新当前用户变量,以便应用更改
var UserStore=require('./UserStore);

var currentuser=UserStore.getUserinfo();
mixins: [
    Reflux.listenTo(UserStore,'onSessionChange'),
    ],
getInitialState() {
    return {
        name: '',
        other: ''
    };
},
componentDidMount() {
    UserActions.getUserInfo();
},
onSessionChange(userInfo) {
    this.setState({
        name: userInfo.name,
        other: userInfo.other
    })
},