我的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();
}
}
在阅读有关渲染调用的React文档后,我有点担心在渲染调用中更改存储,甚至是异步。
我想出了另一种使用componentDidMount和componentDidUpdate的方法。 这最终会稍微复杂一些,因为最初渲染组件时,会调用componentDidMount和componentDidUpdate。 任何后续更新(通过更改URL,然后通过react-router重新呈现) 不会调用componentDidMount,而只调用componentDidUpdate(在初始安装期间也会调用它)。 为避免任何不必要的渲染,需要注意标记。
第二种方法似乎更复杂,涉及更多功能覆盖...
所以问题是:从渲染函数中触发ajax请求有什么问题吗?
谢谢...
render
函数应该是纯粹的 。 这意味着在render
中进行AJAX调用是严格禁止的。 这样做的原因是,如果你的渲染函数可以改变状态,它也可能导致重新渲染,这可能会导致你陷入渲染循环,这将是调试的地狱。
但即使你仔细编写render
函数,以确保你永远不会陷入渲染循环,还有其他理由保持render
纯:React期望render
是纯粹的,所以它不期望状态改变而它正在处理渲染。 虽然你需要检查React的内部结构,但我很确定渲染时改变状态会对渲染性能产生严重影响,因为它需要React中止渲染并在渲染时状态发生变化时重新启动。