在reactjs组件中预加载数据
问题描述:
我正在创建简单的应用程序reactjs/flux方式。 我有MessageStore和UserStore包含该数据:在reactjs组件中预加载数据
MessageStore
包含
[
{"id": 1, "text": "It is a test message", "userId": 155123}
]
UserStore
包含
[
{"id": 155123, "name": "Thomas Brown", "age": 35}
]
我创建组件来显示消息。它需要用户名,但它只有userId从props
获得。
目前我使用的initial-ajax-like approach得到这个数据(警告:ES6反应语法):
componentDidMount() {
var author = UserStore.getById(this.props.userId);
this.setState({
author: author
})
}
render() {
return (<a>{this.state.author.name</a>);
}
它是正确的吗?我发现在这种情况下render
功能被称为两次。 有没有其他方法可以做到这一点?渲染加载图标?避免在检索数据之前进行渲染?
答
每个人都应该移动
var author = UserStore.getById(this.props.userId);
return({
author: author
})
部分getInitialState生命周期。
对于组件的每个实例,getInitialState只会被调用一次,在这里您将有机会初始化实例的自定义状态。与getDefaultProps不同,每次创建实例时都会调用此方法一次。此时你可以访问this.props。
是正确的? 'render'将在初始传递期间被调用一次,然后当你更新'状态'时再被调用。如果您不喜欢这种模式,那么在创建组件之前,您需要预加载数据**。 – WiredPrairie 2015-04-06 12:40:57
@WiredPrairie在做**之前还包括** getIntitialState **调用? – ivstas 2015-04-06 12:56:39
我建议你不能在通常托管组件的任何容器中创建组件。 – WiredPrairie 2015-04-06 13:48:47