javascript - 在 reactjs 组件中预加载数据

标签 javascript reactjs reactjs-flux flux

我正在以 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 函数被调用了两次还有其他方法吗? 渲染加载图标?避免在检索数据之前进行渲染?

最佳答案

一个人应该移动

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/

相关文章:

javascript - ReactJS 状态重置自己

unit-testing - 如何在每次 Jest 测试运行之前运行一些配置

javascript - 在 React JS 中处理关键事件

javascript - 如何使用 getDay() 比较天数

javascript - 无法将 json 文件数据渲染为 html

javascript - 选择元素点击上的JQuery点击事件在chrome中不起作用(在windows环境中不会出现问题)

javascript - 关于用户通过单击按钮触发的 React Hooks 和 AJAX 调用的困境

javascript - 过滤器不适用于 React 中具有 null 值的对象

reactjs - 何时将 Flux(等)与 React 一起使用?

javascript - 停止点击倒计时