【发布时间】:2020-07-20 05:20:47
【问题描述】:
我正在对返回包含详细信息的 JSON 数组的后端脚本进行 axios 调用。后端脚本如下:
app.get('/getAllData', cors(), function (req, res) {
findAll().then((result) => {
// res.writeHead(200)
res.setHeader("Content-Type","application/json")
res.send(result)
res.end()
})
});
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
findAll() 是从数据库中读取数据并返回数组的异步函数。我已经多次点击 URL 并得到了结果。
现在,当我尝试从 react 前端进行 axios 调用时,结果在浏览器的控制台中显示良好。但是当我尝试将结果存储在类的状态中时,它会导致应用程序崩溃。这是下面的反应函数:
makeSongCards = () => {
axios.get("http://localhost:5000/getAllData")
.then((result) => {
const data = result.data
console.log(result.data);
// this.setState({res:data})
})
.catch(err=>console.log(err));;
还有 P.S.出于某种原因,console.log(result.data); 语句在浏览器的控制台中打印了两次。我不知道它是否相关,但我觉得很奇怪。
更新:
初始状态:
constructor(props) {
super(props);
this.state = { res: [] }
}
【问题讨论】:
-
setState 后能否给出错误信息?
-
也分享你的初始状态
-
@kadash setState 之后没有错误消息。一切正常,但是当我使用浏览器加载页面时,console.log 行继续打印。
-
@MonzoorTamal 我已经添加了初始状态
-
@AniruddhaBera 这就是问题所在。如果你使用钩子,那么使用调用useEffect下的fn。如果您基于类,则使用 componentDidMount 并调用 fn