提问者:小点点

使React Js Fetch函数同步调用


我正在编写一个react js代码,其中我正在通过前端的API调用更新nodejs变量。 在这个调用之后,我调用另一个get API来获取这个变量,但是我的fetch是异步调用的,并且我没有获取变量的更新值。 除了我的fetch被异步调用之外,其他一切都正常工作。 请帮我在最后一次调用这个fetch函数。 这是我的密码。

fetch('http://localhost:5000/getId')
  .then(res => res.json())
  .then(
    (result) => {
      this.setState({
        zoomid: result
      });      
      const id=this.state.zoomid
      fetch(`http://localhost:5000/users/zoom?name=${id}`)
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            zoomdata: result,
          });
        },
        (error) => {
          this.setState({ error });
        }
      )
    },
    (error) => {
      this.setState({ error });
    })

共1个答案

匿名用户

.setstate不是同步操作,因此不能使用const id=this.state.zoomid,可以使用result。 此外,你的承诺应该是连锁的,而不是嵌套的。 示例:

fetch('http://localhost:5000/getId')
    .then((res) => res.json())
    .then((result) => {
        this.setState({ zoomid: result });
        return fetch(`http://localhost:5000/users/zoom?name=${result}`);
    })
    .then((res) => res.json())
    .then((result) => {
        this.setState({ zoomdata: result });
    })
    .catch((error) => {
        this.setState({ error });
    });