React componentDidMount vs getInitialState

时间:2015-06-30 19:12:17

标签: javascript reactjs

我对反应的使用和模式有一些疑问。

我应该使用

componentDidMount

getInitialState

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

我正在使用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;

更新:感谢您的回复

This Question建议我们不要 componentWillMount ,但我知道在这种情况下使用 componentDidMount 更具表现力 getInitialState 似乎意味着同步使用

更新2:

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

3 个答案:

答案 0 :(得分:9)

componentDidMount would 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)

getInitialState would 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

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

答案 1 :(得分:3)

在渲染之后触发Componentndid mount,我们在其中加载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>);
            }
        }

答案 2 :(得分:1)

我不确定这种Backbone用法,但是如果你在componentDidMount中加载数据很好,因为基本上代码将在最初呈现组件后开始执行 - 在数据之后获取并再次设置状态,组件将重新呈现,在该点显示正确的数据。这种对我来说很懒散。

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

componentWillMount可能是您想要的,但请查看React lifecycle,了解您认为最有意义的内容。