javascript - 如何使用 React 在渲染中访问数组?
问题描述
我对 React 很陌生,在尝试解决编码问题时,我在另一个问题上看到了这段代码(我尝试询问那些回答了这个问题但没有收到回复的人,因为它在不久前得到了回答):
let theArray = []
functionName(() => {
axios
.get(`/api/data`)
.then(res => {
const newItem = {
id: res.data.id,
name: res.data.name,
};
theArray.push(newItem);
})
}, [])
有人知道如何在 render() 中访问 theArray 吗?我尝试做 theArray[0].id,但出现错误。我也试过this.state.theArray[0].id,但也出错(数组有4个元素,每个元素都有自己的id和名称)
提前感谢您的帮助!
解决方案
你可以写这样的东西。
const [theState, setState] = useState([])
functionName(() => {
axios
.get(`/api/data`)
.then(res => {
const newItem = {
id: res.data.id,
name: res.data.name,
};
setState([...theState, newItem])
})
}, [])
推荐阅读
- python - 如何使用Python将excel文件数据动态转换为json文件
- tomcat - 在tomcat上部署grpc jar
- c# - 无法从 SelectList Razor Pages 中获取选定的值
- javascript - 背景没有相对于滑块正确改变
- android - 我需要在android的分页中使用的数据源
- python - 如何概括python中所有字符串的给定代码?
- javascript - 如何在 html li 标记中呈现快速验证器映射的错误值
- javascript - 尝试根据游戏是否结束来更改文本 react.js
- angular - 如何从 Angular 获取 OneDrive API 的访问令牌
- java - 无法建立与数据库的连接