React update state variable with JSON data(使用 JSON 数据反应更新状态变量)
问题描述
App.js:
function App() {
const [items, setItems] = useState([]);
useEffect(() => {
const searchDB = () => {
fetch("http://127.0.0.1:8443/subColumns/5/?key=fc257229-8f91-4920-b71f-885403114b35", {
mode: 'cors',
credentials: 'include'
})
.then(res => res.json())
.then((json) => {
setItems(json);
})
console.log({items});
}
searchDB();
}, [])
我需要将 json 响应保持在状态变量中,因为在未来,API 请求将不会被硬编码,我希望用户会在不刷新的情况下发出多个 API 请求,结果必须映射到不同的组件.目前,尝试将 {items} 打印到控制台会返回一个空数组.
I need to keep the json response in a state varibale because in the future, the API request will nt be hard coded and I expect the user will make multiple API requests without refreshing, and the results will have to be mapped to different components. At the moment, trying to print {items} to the console returns an empty array.
推荐答案
由于 setItems
是异步方法,所以无法在 setItems 之后立即获取更新的值.您应该使用另一个具有依赖关系的 useEffect
来查看该值.
Since setItems
is the asynchronous method, you can't get the updated value immediately after setItems. You should use another useEffect
with dependency to see the value.
useEffect(() => {
console.log(items);
}, [items]);
这篇关于使用 JSON 数据反应更新状态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JSON 数据反应更新状态变量


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01