React无法设置未定义的属性。

3

我正在使用axios进行get请求。我确定当我发出get请求时,我会得到正确的数据。

在我的构造函数中有一个数组(allQuotes)。然而,当我尝试在componentDidMount中引用它时,它是未定义的。

class App extends Component {

  constructor() {
    super();
    this.allQuotes = [];
  }

  componentDidMount() {

    axios.get("http://getquote.herokuapp.com/get")
    .then(function (response) {
      this.allQuotes = response.data;
      console.log(response.data);
      this.getNewQuote();
    })
    .catch(function (error) {
      console.log("Error: ", error);
      //console.dir(error);
    });
  }

运行后,控制台提示“无法将属性'allQuotes'设置为未定义”。

为什么this 是未定义的呢?


2
这是因为作用域的原因,then() 内部的 this 不是父函数的 this,你需要绑定它,在传递给 then() 的函数末尾添加 .bind(this) - LuisEgan
这位先生说得对。请阅读此文章。它的第一行正是“JavaScript中this关键字的行为已经困扰开发者多年。”,而这正是你所需要的。 - Mark E
3个回答

2

如果您将allQuotes放在状态中,然后使用setState,效果会更好。

class App extends Component {

  constructor() {
    super();
    this.state = {
      allQuotes: [],
    }
  }

  componentDidMount() {

    axios.get("http://getquote.herokuapp.com/get")
    .then(function (response) {
      this.setState({ allQuotes: response.data })
      console.log(response.data);
      this.getNewQuote();
    })
    .catch(function (error) {
      console.log("Error: ", error);
      //console.dir(error);
    });
  }

1
你可以使用箭头函数来解决这个问题。问题是因为如果使用另一个函数,this会指向该函数,而箭头函数没有自己的this,而是继承了其引用者的this
axios.get("http://getquote.herokuapp.com/get")
    .then((response)=>{
     ...
    })
    .catch( (error)=> {
     ...
    });

0

由于您正在使用React,请利用状态(state)。

什么是状态(state)?

状态(state)是组件内的普通JavaScript对象,您可以使用setState将值存储在组件内。您可以参考https://reactjs.org/docs/faq-state.html

  state = {
           allQuotes: []
         }

          componentDidMount() {

            axios.get("http://getquote.herokuapp.com/get")
            .then(function (response) {
              //this.allQuotes = response.data;
              this.setState({
                  allQuotes: response.data
              })
              console.log(response.data);

              this.getNewQuote();
            })
            .catch(function (error) {
              console.log("Error: ", error);
              //console.dir(error);
            });
          }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接