useState 使用问题
来源:14-2 虚拟DOM与React18新的渲染写法

hdjs
2022-11-23
老师,使用useState有个报错,不知道是不是使用方式不对,辛苦帮忙看下
App.jsx内容如下:
import { useEffect, useState } from 'react'
import axios from 'axios'
function App() {
const [loading, setLoading] = useState(true)
const [items, setItems] = useState([])
useEffect(() => {
setTimeout(() => {
const data = [
{
"label": "current",
"key": 1
},
{
"label": "history",
"key": 2
}
]
console.log("获取后端数据")
data.map(item => {
console.log("当前数据: ", item)
setItems([...items, item])
})
setLoading(false)
}, 3000)
}, [])
if (loading) {
return <div>loading...</div>
}
return (
<>
<div>demo</div>
<h2>items: {items}</h2>
</>
)
}
export default App
报错如下:
Uncaught Error: Objects are not valid as a React child (found: object with keys {label, key}). If you meant to render a collection of children, use an array instead.
写回答
2回答
-
西门老舅
2022-11-23
还有就是你这代码有不规范的地方,可以好好看看第15章,函数组件
042022-11-23 -
西门老舅
2022-11-23
你好,这个意思就是{ items }这个是数组,数组里是对象,这个在模板中是没办法直接渲染的,你可以 { items.map(v=> v.label) }
00
相似问题