reactjs - 如何在使用 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)
});
}
解决方案
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
功能之外的东西。
推荐阅读
- css - Scala:CSS颜色字符串到RGB整数的最简洁转换
- cordova - 如何从 Cordova iOS 插件实现 UIWebViewDelegate?
- c# - 创建/使用属性来获取会话变量 C#
- xslt - 有没有办法在 renderX (XSLT) 中的两个流段之间添加一条直线
- python - Python-数据帧循环函数解密
- tensorflow - 运行 TensorFlow label_image 示例会引发访问冲突
- angular - 如何在不使用 npm 的情况下以角度在本地托管引导程序
- vba - IE VBA打开网页等于点击第一个网页链接
- php - 在具有 polylang 支持的 wordpress 中为登录用户和来宾用户设置不同的页面
- dart - DARTFMT 搞乱了@Component 装饰器格式