【发布时间】:2020-05-07 21:25:19
【问题描述】:
我想设置状态变量books 作为 API 的结果。我不能在componentDidMount 中做到这一点,因为我一开始没有令牌,需要它从 API 中获取结果。当我运行以下代码时,状态 books 没有任何反应。如果我在返回之前输入state.books=res.data,我会得到一个结果,但是在手动刷新页面之后。
constructor(props) {
super(props);
this.state = {
books: [],
};
}
和
static getDerivedStateFromProps(nextProps, state) {
if (nextProps.token){
axios.defaults.headers = {
"Content-Type": "application/json",
Authorization: "Token " + nextProps.token
}
axios.get('http://127.0.0.1:8000/api/book/own/')
.then(res => {
return {
books: res.data,
}
})
}
来自 API 的数据如下所示:
{
id: 66,
isbn: "9780545010221",
title: "Title",
author: "Author,Author",
}
在渲染方法中,我使用this.static.books 数据调用组件。
你能告诉我吗?
【问题讨论】:
-
state.books是一个数组,res.data似乎是一个对象。 -
不要获取
getDerivedStateFromProps,使用其他生命周期钩子,例如componentDidUpdate。 -
使用
componentDidMount和componentDidUpdate。 getDerivedStateFromProps 用于高级用例,而不是用于执行异步操作。
标签: javascript reactjs frontend