【问题标题】:React - getDerivedStateFromProps and axiosReact - getDerivedStateFromProps 和 axios
【发布时间】: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
  • 使用componentDidMountcomponentDidUpdate。 getDerivedStateFromProps 用于高级用例,而不是用于执行异步操作。

标签: javascript reactjs frontend


【解决方案1】:

这是一个非常常见的陷阱:您在 Promise 处理程序 (then) 中返回了一些内容,认为这将从创建该 Promise 的函数 (getDerivedStateFromProps) 中返回。事实并非如此。

恐怕您不能将getDerivedStateFromProps 用于这样的异步代码。但是,您不必这样做,因为 react 是,嗯,反应性的。

componentDidUpdate() {
  if (this.props.token) {
    axios.get('http://127.0.0.1:8000/api/book/own/')
      .then(res => this.setState({books: res.data})) ;
  }
}

【讨论】:

  • 这将获取每个更新,因为您没有验证值是否更改,只是检查它是否存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2021-03-09
  • 2023-03-26
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多