![](/img/trans.png)
[英]Not able to show fetched data from firebase into reactjs webapp
[英]Problem rendering fetched data with reactjs and firebase
我正在尝试获取包含看起来像这样的 JSON 数组的数据
[
{
"prof": "Jason Crank",
"views": "2",
//etc etc
}
]
and I'm trying to transform the JSON object into an JavaScript array I can map and render the appropriate amount of blocks, I'm using typescript and this is my code
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.
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.
我将不胜感激,如有必要,我可以提供更多代码片段
总结一下你在上面的评论中被告知的内容......
fetchNotes
functionuseEffect
执行fetchNotes
const Notes: React.FC = () => {
const [notesArr, setNotesArr] = useState<notesInterface[]>([])
useEffect(async () => {
try {
const response = await fetch("my server")
if (!response.ok) {
throw new Error(`${response.status}: ${await response.text()}`)
}
setNotesArr(await response.json())
} catch (err) {
console.error(err)
}
})
return (
<div>
{notesArr.map(note => <NoteThumb {...note} />)}
</div>
)
}
我也清理了你的fetch()
调用; GET
是默认方法,由于没有请求正文, GET
请求没有Content-type
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.