【发布时间】: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>;
}
});
【问题讨论】: