【问题标题】:Preload data in reactjs component在 reactjs 组件中预加载数据
【发布时间】:2015-06-10 19:26:21
【问题描述】:

我正在以 reactjs/flux 的方式创建简单的应用程序。 我有包含这些数据的 MessageStoreUserStore

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 函数被调用了两次还有其他方法可以做到这一点吗? 渲染加载图标?避免在检索数据之前渲染?

【问题讨论】:

  • 什么是正确的? render 将在初始传递期间调用一次,然后在您更新 state 时再次调用。如果您不喜欢这种模式,则需要创建组件之前预加载数据。
  • @WiredPrairie before 是否还包括 getIntitialState 调用?
  • 我建议您不能在通常托管组件的任何容器中创建组件。

标签: javascript reactjs reactjs-flux flux


【解决方案1】:

应该移动

var author = UserStore.getById(this.props.userId);
return({
    author: author
})

getInitialState LifeCycle 的一部分。

getInitialState 对组件的每个实例只调用一次,在这里您有机会初始化实例的自定义状态。与 getDefaultProps 不同,此方法在每次创建实例时调用一次。此时您可以访问 this.props。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2021-03-09
    • 2015-12-04
    相关资源
    最近更新 更多