javascript 反应 componentDidMount 与 getInitialState

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31146524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:21:43  来源:igfitidea点击:

React componentDidMount vs getInitialState

javascriptreactjs

提问by Dan Baker

I have some questions about react usage and patterns.

我有一些关于反应用法和模式的问题。

Should I use

我应该使用

componentDidMount

or

或者

getInitialState

in loading data asynchronously? What is the difference between the two?

在异步加载数据?两者有什么区别?

I am using Backbone for my frontend data structures

我在前端数据结构中使用 Backbone

this.props.data = new BrandModel({ _id: this.props.params.brandId });
var that = this;
this.props.data.fetch({
  success: function () {
    that.setState({ brand: that.props.brand });
  }
});
return null;

Update:thanks for the responses

更新:感谢您的回复

This Questionis suggesting to not us componentWillMount, but I understand that its more expressive to use componentDidMountin this case as getInitialStateseems to be meant to be used synchronously

这个问题建议不是我们componentWillMount,但我知道在这种情况下使用componentDidMount更具表现力,因为getInitialState似乎意味着同步使用

Update 2:

更新 2:

I've had to revert to using getInitialState as componentDidMount fires after render and I need this.props.data to be pointing to an object

我不得不恢复使用 getInitialState 作为 componentDidMount 在渲染后触发,我需要 this.props.data 指向一个对象

回答by Bogdan Savluk

componentDidMountwould be called after component was mounted into browser DOM (it would be called after first render and it would not be called if you are rendering server-side(to string)

componentDidMount将在组件安装到浏览器 DOM 后调用(它将在第一次渲染后调用,如果您正在渲染服务器端(到字符串),则不会调用它

getInitialStatewould be called when component is created, if you are using es6 class syntax you can place that logic in you component constructor directly assigning to this.state

getInitialState将在创建组件时调用,如果您使用 es6 类语法,您可以将该逻辑放置在组件构造函数中,直接分配给 this.state

There is also componentWillMountit would be called before first render for both server and client - it is more suitable in your case.

还有componentWillMount它会被调用之前先渲染服务器和客户端-这是更适合你的情况。

回答by Rajat banerjee

Componentndid mount is fired after the render and we load the Ajax inside that.While during the actual render we check if the object has data, else send empty div

在渲染之后触发 Componentndid 装载,我们在里面加载 Ajax。在实际渲染期间,我们检查对象是否有数据,否则发送空 div

componentDidMount: function () {
            console.log("========> FIring");
            $.get("http://api.", function(response) {
                if (this.isMounted()) {
                    this.setState({
                    Data: response
                });
                }
            }.bind(this));
        },
        render: function() {
            var data = this.state.Data;
            if (this.state.promoData) {
             return (<div>{data}</div>
            );
            } else {
              return (<div className="divLoading">Loading...</div>);
            }
        }

回答by Joseph Furlott

I'm not sure about this Backbone usage but if you load data in componentDidMountthat's fine as essentially that code will start executing after the component is initially rendered -- after the data is fetched and the state is set again, the component will re-render showing that correct data at that point. This kind of like lazy loading to me.

我不确定这个 Backbone 的用法,但如果你加载数据componentDidMount那很好,因为基本上代码将在组件最初呈现后开始执行——在获取数据并再次设置状态后,组件将重新呈现在那一点显示正确的数据。这对我来说有点像延迟加载。

I'm not sure if getInitialStateis blocking, but if it is, then the component will not render until the state is loaded. But I think it isn't, so the data would probably not be fetched by the time the component is rendered.

我不确定是否getInitialState正在阻塞,但如果是,则在加载状态之前组件不会呈现。但我认为它不是,因此在呈现组件时可能不会获取数据。

componentWillMountmay be what you want, but review the React lifecyclefor what you think makes the most sense.

componentWillMount可能是您想要的,但请查看React 生命周期以找出您认为最有意义的内容。