反应这是未定义的

时间:2016-07-07 06:06:34

标签: reactjs this

在承诺中未定义React this。这是我的代码:

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 个答案:

答案 0 :(得分:10)

可能它没有约束this

如果您能够使用ES6语法,请尝试替换为arrow functions。它会自动绑定它:

.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) )

答案 1 :(得分:4)

您可以将this绑定到thoes功能中。 或者您也在self = this函数中声明componentDidMount。然后在self

中使用this axios的instand

答案 2 :(得分:2)

示例:

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>
    );
  }
}

或者您可以使用此模块auto-bind