简体   繁体   English

ReactJS:为什么约定在componentDidMount上获取数据?

[英]ReactJS: Why is the convention to fetch data on componentDidMount?

As per this link https://facebook.github.io/react/tips/initial-ajax.html , 按照此链接https://facebook.github.io/react/tips/initial-ajax.html

I've built a todo app that works great. 我建立了一个很棒的待办事项应用程序。 I fetch my data in componentDidMount hook like they say to. 我像他们说的那样在componentDidMount挂钩中获取数据。 I just had a question on the why. 我只是有一个关于为什么的问题。

Why do we fetch data after the components mounted? 为什么在安装组件后获取数据? Seems to me it just ends up re-rendering once the data gets set in setState() in the hook. 在我看来,一旦在钩子中的setState()中设置了数据,它就最终会重新呈现。

Why not just fetch the data in constructor() and set the initial state with data? 为什么不只是在constructor()获取数据并使用数据设置初始状态? Wouldn't that be just the 1 render? 那不就是1个渲染器吗? Seems less expensive even if its only partially re-rendering because of the virtual DOM. 即使由于虚拟DOM而仅部分重新渲染,它似乎也较便宜。

The fetch will generally be executing asynchronously so it's always going to cause a second render despite it being within componentWillMount or componentDidMount . 提取通常会异步执行,因此尽管它位于componentWillMountcomponentDidMount但始终会导致第二次渲染。

I believe they are recommending to put it within the componentDidMount as you may be using a browser dependant implementation of sorts. 我相信他们建议将其放在componentDidMount因为您可能正在使用依赖于浏览器的各种实现。 When executing/rendering components on the server (ie within node) only componentWillMount gets executed, and therefore could fall over if you are using a browser/DOM dependant feature. 在服务器上(即节点内)执行/渲染组件时,仅componentWillMount被执行,因此如果您使用的是浏览器/ DOM相关功能,则可能会崩溃。 The other lifecyle methods (ie componentDidMount ) don't get executed on the server, so hence the safety and recommendation I think. 其他生命周期方法(即componentDidMount )不会在服务器上执行,因此我认为是安全和推荐的。 Although in general I have found it more useful when needing to do DOM access. 尽管总的来说,我发现它在需要进行DOM访问时更有用。 Use a universal ajax library (ie runs on node/browser) and this probably won't be a concern for you. 使用通用的ajax库(即在节点/浏览器上运行),这可能对您而言不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM