【问题标题】:React componentDidMount vs getInitialState反应 componentDidMount 与 getInitialState
【发布时间】:2015-09-17 17:41:20
【问题描述】:

我对 React 的用法和模式有一些疑问。

我应该使用

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 指向一个对象

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    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】:

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

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

      还有componentWillMount,它会在服务器和客户端第一次渲染之前被调用——它更适合你的情况。

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

        • getInitialState 没有阻塞——没有 React 函数是阻塞的,除非有人做类似 while (true) { console.log('a-long-loop'); } 的事情
        猜你喜欢
        • 2015-09-03
        • 2015-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-05
        • 2014-12-24
        • 2021-05-22
        • 2016-09-03
        相关资源
        最近更新 更多