小编典典

反应这是未定义的

reactjs

React this在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

阅读 276

收藏
2020-07-22

共1个答案

小编典典

可能没有约束力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) )
2020-07-22