首页 > 解决方案 > 从窗口获取路径名并将其存储在状态中以在 fetch 函数中使用

问题描述

我有以下功能:

  fetchData = () => {
      fetch('/api/customerNodes' + this.state.number)
          .then(response => response.text())
          .then(message => {
              this.setState({responseText: message});
          });
    };

如果我将浏览器指向localhost:3000/1234并且我想获得 1234 的路径名,我会做这样的事情。const num = window.location.pathname;

我面临的问题是我无法将该值设置为状态。

  componentDidMount() {
    const num = window.location.pathname;
    this.setState({ number: num });
    console.log(this.state.number);
    //setInterval(this.fetchData, 250);
  }

console.log是空的。

我究竟做错了什么?

标签: reactjs

解决方案


使用回调函数this.setState

const num = window.location.pathname;

this.setState({ number: num }, () => {
  console.log(this.state.number, 'number');
}); 

setState() 通常是异步的,这意味着在您控制台记录状态时,它还没有更新。通过将日志放在 setState() 方法的回调中,它会在状态更改完成后执行。


推荐阅读