我可以把ajax放到React组件构造函数中吗?

时间:2022-08-22 20:22:16

class AjaxInConstructor extends React.Component{
    constructor() {
        super();
        this.state = {name: '', age: ''}
        this.loadData().then(data => {
            this.setState(data);
        });
    }
    loadData() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve({
                    name: '我去去去去nimabi',
                    age: 123
                });
            }, 2000);
        });
    }
    render() {
        const {name, age} = this.state;
        return <div>
            <p>Can I init component state async?</p>
            <p>name: {name}</p>
            <p>age: {age}</p>
        </div>
    }
}

ReactDOM.render(
  <AjaxInConstructor/>,
  document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Above is my demo code. I know people always put ajax in componentDidMount or componentWillMount lifecycle.

上面是我的演示代码。我知道人们总是把ajax放到componentDidMount或componentWillMount生命周期中。

But this case also works.

但这个例子同样有效。

In chrome console, React throw no error and waring. So, My Question is usage like this is completely correct ? Is there have some error?

在chrome控制台,反应抛出没有错误和警告。我的问题是这样的用法完全正确吗?有什么错误吗?

1 个解决方案

#1


13  

You can make an AJAX call wherever you want. There is nothing "wrong" in making an AJAX call in the constructor, but there is a catch. You'll want to make the AJAX call only after the component has been mounted or just before it is about to be mounted.

您可以在任何需要的地方进行AJAX调用。在构造函数中进行AJAX调用没有什么“错误”,但是有一个问题。您将只希望在组件已挂载或即将挂载之前进行AJAX调用。

So before component is rendered, making an AJAX call in componentDidMount() or componentWillMount() is recommended. Just because React allows to do "things" does not mean you should! :)

因此,在呈现组件之前,建议在componentDidMount()或componentWillMount()中进行AJAX调用。仅仅因为反应允许做“事情”并不意味着你应该!:)

UPDATE

更新

I also realize that initially my answer wasn't rigorous. I have always followed what fellow programmer have followed, blindly.

我也意识到最初我的答案并不严谨。我总是盲从程序员的跟班。

After searching a bit I found these to be one step closer to the complete answer- Why ajax request should be done in componentDidMount in React components?

在搜索了一些之后,我发现这些都是更接近完整答案的一步——为什么ajax请求应该在组件的组件中完成?

Essence of those answer says that when you call setState() in componentWillMount(), the component will not re-render. Therefore one must use componentDidMount(). After further reading I learned that it was fixed in subsequent release by React team. You can now call setState() in componentWillMount(). I think that is the reason why everyone recommends making AJAX calls in didMount.

这些答案的本质是,当您在componentWillMount()中调用setState()时,组件将不会重新呈现。因此,必须使用componentDidMount()。在进一步阅读之后,我了解到它在随后的发布中被React team修复了。现在可以在componentWillMount()中调用setState()。我认为这就是为什么每个人都建议在didMount中进行AJAX调用。

One of the comments also puts forth my thoughts very articulately-

其中一篇评论也非常清晰地提出了我的想法

well, you are not calling setState from componentWillMount nor componentDidMount directly, but from a new async stack. I have no idea how exactly react is implemented to keep reference to this with live event listeners from various methods. if using undocumented features is not scary enough for you and want a bit of excitement that it might work and maybe even in future versions, then feel free, I don't know whether it will break or not

您不是直接从componentWillMount或componentDidMount调用setState,而是从一个新的异步堆栈。我不知道如何准确地实现response,以便与来自不同方法的活动事件侦听器保持引用。如果使用未文档化的特性对您来说还不够可怕,并且希望它能够工作,甚至可能在将来的版本中工作,那么请放心,我不知道它是否会崩溃

#1


13  

You can make an AJAX call wherever you want. There is nothing "wrong" in making an AJAX call in the constructor, but there is a catch. You'll want to make the AJAX call only after the component has been mounted or just before it is about to be mounted.

您可以在任何需要的地方进行AJAX调用。在构造函数中进行AJAX调用没有什么“错误”,但是有一个问题。您将只希望在组件已挂载或即将挂载之前进行AJAX调用。

So before component is rendered, making an AJAX call in componentDidMount() or componentWillMount() is recommended. Just because React allows to do "things" does not mean you should! :)

因此,在呈现组件之前,建议在componentDidMount()或componentWillMount()中进行AJAX调用。仅仅因为反应允许做“事情”并不意味着你应该!:)

UPDATE

更新

I also realize that initially my answer wasn't rigorous. I have always followed what fellow programmer have followed, blindly.

我也意识到最初我的答案并不严谨。我总是盲从程序员的跟班。

After searching a bit I found these to be one step closer to the complete answer- Why ajax request should be done in componentDidMount in React components?

在搜索了一些之后,我发现这些都是更接近完整答案的一步——为什么ajax请求应该在组件的组件中完成?

Essence of those answer says that when you call setState() in componentWillMount(), the component will not re-render. Therefore one must use componentDidMount(). After further reading I learned that it was fixed in subsequent release by React team. You can now call setState() in componentWillMount(). I think that is the reason why everyone recommends making AJAX calls in didMount.

这些答案的本质是,当您在componentWillMount()中调用setState()时,组件将不会重新呈现。因此,必须使用componentDidMount()。在进一步阅读之后,我了解到它在随后的发布中被React team修复了。现在可以在componentWillMount()中调用setState()。我认为这就是为什么每个人都建议在didMount中进行AJAX调用。

One of the comments also puts forth my thoughts very articulately-

其中一篇评论也非常清晰地提出了我的想法

well, you are not calling setState from componentWillMount nor componentDidMount directly, but from a new async stack. I have no idea how exactly react is implemented to keep reference to this with live event listeners from various methods. if using undocumented features is not scary enough for you and want a bit of excitement that it might work and maybe even in future versions, then feel free, I don't know whether it will break or not

您不是直接从componentWillMount或componentDidMount调用setState,而是从一个新的异步堆栈。我不知道如何准确地实现response,以便与来自不同方法的活动事件侦听器保持引用。如果使用未文档化的特性对您来说还不够可怕,并且希望它能够工作,甚至可能在将来的版本中工作,那么请放心,我不知道它是否会崩溃