我想在我的React代码中使用axios从服务器获取数据。我像这样将axios代码放在我的react组件的componentWillMount中。


componentWillMount()
    {
        axios
        .get("https://jsonplaceholder.typicode.com/Posts")
        .then(function(response) {
            this.setState({Posts : response.data[0].title});
        })
        .catch(function(error) {
            console.log(error);
        });
    }


但是上面的代码抛出了这样的错误


TypeError: "this is undefined"
    componentWillMount Redux



但是当我在代码中做了些细微的更改(例如下面的代码)时,一切正常。


componentWillMount()
    {
        axios
        .get("https://jsonplaceholder.typicode.com/Posts")
        .then(response= > {
            this.setState({Posts : response.data[0].title});
        })
        .catch(error => {
            console.log(error);
        });
    }


我想说的另一件事是componentWillMount中的“ this”对象处于活动状态

有没有人告诉我上面两个代码之间的区别?

最佳答案

绑定功能或使用箭头功能

componentWillMount = () => {

  axios("https://jsonplaceholder.typicode.com/Posts")
    .then((response) => {
      this.setState({ Posts: response.data[0].title });
    })
    .catch(function (error) {
      console.log(error);
    });
}


编辑

请使用componentDidMount代替componentWillMount

componentDidMount = () => {}


或将此值保存在变量中。

componentDidMount = () => {

  const that = this;

  axios("https://jsonplaceholder.typicode.com/Posts")
    .then(function (response) {
      that.setState({ Posts: response.data[0].title });
    })
    .catch(function (error) {
      console.log(error);
    });
}


演示



<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="root"></div>

<script type="text/babel">

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      Posts: '',
    };
  }

    componentDidMount = () => {
      const that = this;
      axios("https://jsonplaceholder.typicode.com/Posts")
        .then(function (response) {
          that.setState({ Posts: response.data[0].title });
        })
        .catch(function (error) {
          console.log(error);
        });
    }

  render() {
    return (
      <div>
        <p>Post title</p>
        <p>{this.state.Posts}</p>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
</script>





这个

这是在运行时确定的,具体取决于代码,可能有所不同。

这是


在运行时确定何时调用函数
取决于函数的调用方式,而不是函数的位置
定义的
对对象的引用。
将永远是一个对象
全局(此)在严格模式下不可用


范例1:this = window


var name = 'Global';

var callName1 = function() {
  var name = 'Peter';
  console.log('--- From callName1 ----');
  console.log(this.name);
  //console.log(this);
  callName2();
}


var callName2 = function() {
  var name = 'Jane';
  console.log('--- From callName2 ----');
  console.log(this.name);
  //console.log(this);
}

callName1();

var execute = function(fn) {
  var name = 'Mary';
  console.log('--- From execute ----');
  console.log(this.name);
  //console.log(this);
}

execute(callName2);





示例2:在严格模式下不可用



'use strict';

var name = 'Global';

var callName1 = function() {
  var name = 'Peter';
  console.log('--- From callName1 ----');
  console.log(this.name);
  console.log(this);
}

callName1();





示例3:使用方法调用进行检查



var name = 'global';

var obj = {
  name: 'James Obj1',
  func: function() {
    console.log('--- From func ----');
    console.log(this.name);
    console.log(this); // this reference obj1
  }
}

obj.func()

var obj2 = {
  name: 'Jame Obj2',
  func: obj.func // this reference obj2, but the function is defined in obj1
}

obj2.func()

var obj3 = {
  name: 'Kane Obj3',
  obj4: {
    name: 'Mary Obj4',
    func: function () {
      console.log('--- From obj4 ----');
      console.log(this.name);
      console.log(this); // this reference obj4
    }
  }
}
obj3.obj4.func()





使用() => {}函数可以-在词法上绑定。这意味着它使用包含箭头功能的代码中的this

07-24 09:44
查看更多