React文档指出应从componentDidMount生命周期事件启动ajax请求 (请参阅react docs)。
componentDidMount
为什么会这样?
在大多数情况下,使用ajax加载数据时,我想显示某种加载栏,例如:
componentDidMount() { this.setState({isLoading: true}); fetch(...) .then(...) .then(() => this.setState({isLoading: false}) }
但这会触发render方法3次(初始渲染后立即进行设置isLoading = true,然后按isLoading = false
render
isLoading = true
isLoading = false
从componentWillMount事件发送Ajax请求有什么问题?
componentWillMount
好吧,isLoading: true可能是初始状态的一部分,无需在组件完成mount =>后设置它,只需设置2个渲染,而不是3个。
isLoading: true
根据https://github.com/reactjs/react- redux/issues/210的说法,render仅从from 调用一次的结果componentWillMount意味着,如果setState将在after之后被异步调用render,则不会有任何效果(如果我正确理解了注释)。
setState
不知道回调是否有可能在setState执行之前执行render,因此看不到加载屏幕,只有结果可见,因此有时它会“起作用”(很有可能在DEV中),但实际上这将是一个竞争条件难以调试…
另请参阅:https : //reactjs.org/docs/faq-ajax.html