【发布时间】:2021-04-26 00:03:52
【问题描述】:
我正在尝试获取包含如下所示 JSON 数组的数据
[
{
"prof": "Jason Crank",
"views": "2",
//etc etc
}
]
我正在尝试将 JSON 对象转换为一个 JavaScript 数组,我可以映射和渲染适当数量的块,我正在使用 typescript,这是我的代码
const [notesArr, setNotesArr] = useState<notesInterface[]>([])
const fetchNotes = async (active) => {
try{
const response = await fetch("my server", {
method:"GET",
headers: {'Content-Type': 'application/json'}
})
.then(resp => JSON.parse(JSON.stringify(resp)))
.then(result => setNotesArr(result))
return(
<div>
{notesArr.map((notes) => <NoteThumb link={notes.link} title={notes.title} semester={notes.semester} prof={notes.prof} timestamp={notes.timestamp} likes={notes.likes} views={notes.views} pages={notes.pages} isBookmarked={notes.isBookmarked}/>)}
</div>
)
}catch(error){
console.log(error)
}
}
我使用的界面是这样的
interface notesInterface {
prof: string
views: number
}
尝试此操作时,我收到一条错误消息,上面写着Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
如果有任何帮助,我将不胜感激,如有必要,我可以提供更多我的代码的 sn-ps
【问题讨论】:
-
将您的
return (...)移出fetchNotes函数。你在哪里打电话给fetchNotes? -
@Phil 我在函数组件的返回中调用它
-
@Phil 它是反应函数组件中的一个函数
-
你能发布你的
<NoteThumb />组件吗? -
为了获取数据,你应该使用useEffect钩子并在那里调用你的函数fetchNotes,并在你的函数中删除渲染,它必须在return语句中。
标签: javascript reactjs firebase