react这是未定义的

IT技术 reactjs this
2021-04-13 21:30:08

Reactthis在 promise 中是未定义的。这是我的代码:

export default class Album extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount ()  {
        console.log(this.props.route.appState.tracks);  // `this` is working
        axios({
            method: 'get',
            url: '/api/album/' + this.props.params.id + '/' + 'tracks/',
            headers: {
                'Authorization': 'JWT ' + sessionStorage.getItem('token')
            }
        }).then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
        }).catch(function (response) {
            console.error(response);
            //sweetAlert("Oops!", response.data, "error");
        })
    }

这是错误代码:

TypeError: this is undefined
Stack trace:
componentDidMount/<@webpack:///./static/apps/components/Album.jsx?:81:17
3个回答

可能它没有约束力this

如果您能够使用 ES6 语法,请尝试用箭头函数替换它会自动绑定:

.then( (response) => {
        console.log(response.data);
        this.props.route.appState.tracks.concat(response.data); // 'this' isn't working
    } )

或者手动绑定:

.then(function (response) {
            console.log(response.data);
            this.props.route.appState.tracks.concat(response.data);
        }.bind(this) )
我们应该删除// 'this' isn't working评论吗?
2021-05-31 21:30:08

您可以绑定this到 thoes 函数。或者你也声明self = thiscomponentDidMount的功能。然后使用selfinstand of thisinaxios

其他方式:使用箭头函数

例子:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "My_Name"
    };
    this.componentDidMount = this.componentDidMount.bind(this);
  }

  componentDidMount () {
    let node = this.refs.term;
    term.focus();
  }

  render () {
    return (
      <div>
        <input type="text" ref="term" />
      </div>
    );
  }
}

或者你可以使用这个module自动绑定