为什么我在 componentDidMount 中的函数被快速调用?

Why my function in componentDidMount is being called rapidly?

我在 React 中创建了一个函数,它从 Youtube API 获取一些信息,我希望它在我刷新页面并将该信息置于某个状态时只被调用一次。但是当我在 componentDidMount 中使用它时,它不会保存信息并且我的状态仍然是空的。这是代码:

  constructor(props) {
    super(props);
    this.state = { vid: [] };
    this.vidSearch = this.vidSearch.bind(this);
  }
  vidSearch = async () => {
    const youtubeVid = await Youtube.get("/search");
    this.setState({ vid: youtubeVid.data.items });
  };

  componentDidMount() {
    this.vidSearch();
    console.log(this.state.vid);
  }```

setState may be asynchronous,所以您无法立即查看状态。但它有一个可选的回调,您可以使用它,称为 after 该过程已完成。

vidSearch = () => {
  const youtubeVid = await Youtube.get("/search");
  this.setState({ vid: youtubeVid.data.items }, () => {
    console.log(this.state.vid);
  });
};

componentDidMount() {
  this.vidSearch();
}

根据官方文档:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor() instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

在这种情况下,我会将我的代码更改为:

constructor(props) {
    this.state = {
        vid: Youtube.get('/search').data.items
    }
}

vidSearchasync 并且您在调用 console.log 之前没有 awaitcomponentDidMount 中 returned 承诺。

所有 async 函数将 return 值包装在一个承诺中,甚至是隐含的 returns。

你可以试试this.vidSearch().then(() => console.log(this.state)).