【发布时间】:2017-09-24 05:51:49
【问题描述】:
我的 React 组件需要一个 ajax 调用来获取数据来呈现自己。
最初,我使用该方法在渲染中启动 ajax 调用。这是我的伪代码...
export class MyView extends React.Component<any, any> {
hasAjaxData: boolean = false;
renderAndGetData() {
const data = {
};
AjaxCall(data)
.then((results) => {
this.hasAjaxData = true;
// save to store here, causing a rerender
...
});
})
.catch((err: Error) => {
console.error(err);
});
return (
<SpinnerComponent />
);
}
renderWithData() {
return (
<div>
Render with data here
</div>
);
}
render() {
return this.hasAjaxData ? this.renderWithData() : this.renderAndGetData();
}
}
在阅读了有关 render call 的 React 文档后,我有点担心在渲染调用中更改存储,即使是异步的。
我想出了另一种使用 componentDidMount 和 componentDidUpdate 的方法。这最终会稍微复杂一些,因为在最初渲染组件时,componentDidMount 和 componentDidUpdate 都会被调用。任何后续更新(通过更改 URL,然后通过 react-router 重新渲染)都不调用 componentDidMount,而只是调用 componentDidUpdate,(在初始挂载期间也会调用)。为避免任何不必要的渲染,需要特别注意标志。
第二种方法似乎更复杂,涉及更多的函数覆盖......
所以问题是:从渲染函数中触发 ajax 请求有什么问题吗?
谢谢...
【问题讨论】:
标签: ajax reactjs react-router