使用React轮询API并在该轮询后立即设置状态

问题描述 投票:0回答:1

我阅读了很多有关此问题的文章和教程,但似乎与我的情况不符。

我正在一个系统中工作,我需要轮询一些信息并使用此新信息来呈现我的应用程序,我尝试使用componentDidUpdate来完成工作,但是我需要根据收到的每个响应设置状态,然后编写我的代码输入无限循环,浏览器就会冻结...

但是这不是唯一的问题,当我的请求捕获旅行的差异值(viagens)时,我需要将图标从红色闪烁为绿色,然后再将其闪烁为红色。

我知道套接字服务器,但是我有这个API,我不能使用其他东西,我需要一种解决方法,我只是在前端使用,我不知道如何解决这个问题现在。

我的请求代码是这样的

polling(id_maquina){
    fetch(`http://localhost:5000/Arduino/DadosEmpilhadeira?id_maquina=${id_maquina}`)
        .then(res => res.json())
        .then(json => this.setState({maquina: json}));
}

这是我第一次解决此问题:

componentDidUpdate(prevProps, prevState){
    const id_maquina = this.state.nome;
    console.log("entrou no loop");
    setInterval(() => {
        fetch(`http://localhost:5000/Arduino/DadosEmpilhadeira?id_maquina=${id_maquina}`)
            .then(res => res.json())
            .then(json => this.setState({maquina: json}));
    }, 10000);
    if(prevState.maquina.viagens !== this.state.maquina.viagens){
        setInterval(this.setState({cor: 'rgb(0,100,0)'}), 2000);
    }
    setTimeout(() => {
        this.setState({cor: 'rgb(220,0,0)'});
    }, 2000);
}

我根本不是前端或JS方面的专家,但是如果我无法停止在第一个端点之前再次触发componentDidUpdate,我会觉得我的setInterval没有做任何事情。

[编辑]

我的轮询阶段仅在我提交id_maquina值之后开始,这意味着我不知道是否可以将此逻辑放在componentDidMount上,因为在第一次装载时,我将无法执行提取操作,将返回错误400“ “从我的API中获取。

reactjs polling
1个回答
0
投票

您应该在componentDidMount中设置setInterval函数,因为它只能被调用一次。

也请记住清除componentWillUnmount中的间隔

polling() {
    const id_maquina = this.state.nome;
    if (id_maquina) { // check if id is present then only make the call
      fetch(`http://localhost:5000/Arduino/DadosEmpilhadeira? 
           id_maquina=${id_maquina}`)
        .then(res => res.json())
        .then(json => this.setState({ maquina: json }));
    }
  }


componentDidMount(){
    this.intervalID = setInterval(polling, 10000); // you can start polling either on did mount or in you submit event handler
}

componentWillUnmount(){
        clearInterval(this.intervalID);
    }

此外,我认为如果viagens发生变化,您也想这样做(如果我错了,请纠正我)

componentDidUpdate(prevProps, prevState) {
    if (prevState.maquina.viagens !== this.state.maquina.viagens) {
      setTimeout(() => {
        this.setState({ cor: "rgb(220,0,0)" });
      }, 2000);
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.