简体   繁体   English

反应钩子更新 state 未传递给 function

[英]React hooks updated state not passed to function

I am trying to save an api response using react hooksand pass it to a fucntion drawChart.我正在尝试使用反应钩子保存 api 响应并将其传递给功能绘图图。 In this code the update state of the object is not being passed to my function.在此代码中,object 的更新 state 未传递给我的 function。 What would be the proper way of passing the updated state of the object to the function drawChart?将 object 的更新后的 state 传递给 function 绘制图表的正确方法是什么?

  useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
      })
      .then(response=>{
        drawChart(responseMonthly, 'month')
      })
      .catch(err => console.log(err))
  },[]);

when you change your state, the component must be rernder to get new state当您更改 state 时,必须重新渲染组件以获得新的 state

you can write another useEffect like this你可以像这样写另一个useEffect

  useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
      })
      .catch(err => console.log(err))
  },[]);


useEffect(() => {
    if(responseMonthly) drawChart(responseMonthly, 'month')
},[responseMonthly]);

or you can call your function like this或者你可以像这样调用你的 function

 useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
        drawChart(obj, 'month')
      })
      .catch(err => console.log(err))
  },[]);

You need to pass whatever variable you want to change within the []您需要在 [] 中传递要更改的任何变量

    useEffect(() => {
        if (responseMonthly) {
          drawChart(responseMonthly, 'month')
          return 
        }

        axios.get(url)
          .then(response => {
            var obj = JSON.parse(response.data)
            setResponseMonthly(obj);
          })
          .catch(err => console.log(err))
      },[responseMonthly]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM