【问题标题】:Why my function in componentDidMount is being called rapidly?为什么我在 componentDidMount 中的函数被快速调用?
【发布时间】:2021-11-03 21:26:19
【问题描述】:

我正在创建一个函数来从 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);
  }```

【问题讨论】:

  • 您确定调用的是 componentDidMount 而不是其他钩子吗?你可以在 componentDidMount() 的开头添加一个 console.log("This is componentDidMount") 来检查。

标签: javascript reactjs function api state


【解决方案1】:

vidSearchasync 并且在调用 console.log 之前,您不是 awaiting 在 componentDidMount 中返回的承诺。

所有async 函数都将返回值包装在一个promise 中,甚至是隐式返回。

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

【讨论】:

    【解决方案2】:

    根据官方文档:

    您可以立即在 componentDidMount() 中调用 setState()。它会 触发额外的渲染,但它会在浏览器之前发生 更新屏幕。这保证了即使 render() 将 在这种情况下被调用两次,用户不会看到中间 状态。谨慎使用此模式,因为它通常会导致 性能问题。在大多数情况下,您应该能够分配 构造函数()中的初始状态。然而,它可以是 当您需要测量时,对于模态和工具提示等情况是必需的 渲染之前的 DOM 节点,这取决于它的大小或 位置。

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

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

    【讨论】:

      【解决方案3】:

      setState may be asynchronous,因此您将无法立即检查状态。但它有一个可选的回调,您可以使用它在进程完成后调用

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        • 2019-11-05
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        相关资源
        最近更新 更多