官方建议把ajax写到componentdidmount中,
在render之前,在componentwillmount中执行setState不会重新render
但是如果写在componentwillmount中的setState在render之后执行,比如设置了定时器,setState后,也会造成重新render
写在componentdidmount中的ajax,一定是在第一次render之后再render的
既然如上所述,那把ajax写在componentwillmount中不是更好吗?
如果ajax的执行在render之前得到了值,并setState,那就执行一次render。
如果在第一次render之后得到了值,那就如同componentdidmount一样再次render就行,这样有可能还省去一些render。
虽然reactjs的diff算法很快,但两次的render肯定没有一次效率高
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
那是因为服务端渲染时不会执行didmount的代码,把ajax写在此有利于同构
然后你说在第一次render之前得到值什么的,我本地测试都不会有这样的事情发生,更何况在一个实际环境中
在同构的情况下,生命周期会到
componentwillmount,这样使用ajax就会出错,所以之前一个比较好的解决方案是将ajax放在组件挂载的页面上时再去拉取数据,不过目前的解决方案就是利用fetch,有时候考虑问题要在大的方面上啊!还有就是,考虑用户体验,假如向你说的放在componentwillmount中,那么没有数据过来时就是白屏,而放在didmount中可以有一个初始的状态