我正在以 reactjs/flux 方式创建简单的应用程序。 我有包含以下数据的 MessageStore 和 UserStore:
MessageStore
包含
[
{"id": 1, "text": "It is a test message", "userId": 155123}
]
UserStore
包含
[
{"id": 155123, "name": "Thomas Brown", "age": 35}
]
我正在创建组件来显示消息。它需要用户名,但它只有从props
获取的userId。
目前我使用initial-ajax-like approach获取此数据(警告:es6 react 语法):
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 LifeCycle 的一部分。
getInitialState 为组件的每个实例调用一次,在这里您有机会初始化实例的自定义状态。与 getDefaultProps 不同,每次创建实例时都会调用一次此方法。此时您可以访问 this.props。
关于javascript - 在 reactjs 组件中预加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470583/