首页 > 解决方案 > 如何在使用 API 获取数据时更新功能组件中的 React 状态

问题描述

我正在尝试使用 API 更新功能组件中的反应状态,但是不知何故它没有得到更新。我不确定我身边缺少什么。有人可以帮助以下代码片段中缺少的内容。

代码

export default function Test(props) {
const [state, setState] = useState({
    data: []
  });

useEffect(() => {
  getConnectionUsers("Test")
  return () => {alert("component unmount");}
    }, [])
}

function getConnectionUsers(connection) {
    axios.get(URL).then((response) => {
        if (response.status === 200) {
          console.log(response.data);  // This is showing correct data which is coming from API
          setState({...state ,data:response.data});
          console.log(state.data);    //Empty State is coming which means somehow state is not updated properly
        }
    }).catch(error => {
        alert(error)
      });
}  

标签: reactjs

解决方案


export default function Test(props) {
  const [state, setState] = useState({
    data: []
  });

  useEffect(() => {
    getConnectionUsers("Test")
    return () => {alert("component unmount");}
  }, []);

  function getConnectionUsers(connection) {
    axios.get(URL).then((response) => {
        if (response.status === 200) {
          console.log(response.data);  // This is showing correct data which is coming from API
          setState({...state ,data:response.data});
          console.log(state.data);    //Empty State is coming which means somehow state is not updated properly
        }
    }).catch(error => {
        alert(error)
    });
  }  
}

您必须在生命周期中更新您的状态。而且你不能触摸useState功能之外的东西。


推荐阅读