[英]Passing undefined data to React components
I am creating a realtime dashboard which consumes an API for the data.我正在创建一个使用数据 API 的实时仪表板。 The application is an isomorphic react app built on top of a node API, I am using the Flux architecture, more specifically the alt implementation .
该应用程序是一个构建在节点 API 之上的同构 React 应用程序,我使用的是 Flux 架构,更具体地说是alt 实现。
On initial page load I call componentDidMount
and pass the action to fetch data在初始页面加载时,我调用
componentDidMount
并传递操作以获取数据
componentDidMount() {
MyActions.getData();
MyStore.listen(this._onChange);
}
As this is calling an external API there is a delay in fetching the data, this means the state which will house the data is undefined
.由于这是调用外部 API,因此在获取数据时存在延迟,这意味着将容纳数据的状态是
undefined
。 In order to stop the component erroring as I would be passing undefined
data I am currently doing the following:为了阻止组件错误,因为我将传递
undefined
数据,我目前正在执行以下操作:
render() {
let foo;
if(typeof this.state.apiData == "undefined") {
foo = (<div></div>
} else {
foo = (<MyComponent data={this.state.apiData} />)
);
}
Although this works it doesn't feel very elegant, is there a better way to catch undefined
data before rendering components?虽然这有效但感觉不是很优雅,有没有更好的方法在渲染组件之前捕获
undefined
数据?
what you could do is use componentWillMount()
to start fetching the data.您可以做的是使用
componentWillMount()
开始获取数据。 and the check you are doing in your render()
function could look like:您在
render()
函数中所做的检查可能如下所示:
render() {
if (this.state.apiData === undefined) {
return null;
}
return (
<MyComponent data={this.state.apiData} />
);
}
Also as you mentioned that you data changes it might be worth to make use of componentWillReceiveProps()
to check for changes and rerender if needed同样,正如您提到的,您的数据更改可能值得使用
componentWillReceiveProps()
检查更改并在需要时重新渲染
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.