2016-07-07 46 views
0

反应this是承诺中未定义。这里是我的代码:反应这是undefined

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语法,请尝试替换为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); // 'this' isn't working 
     }.bind(this)) 
1

可以绑定到this功能thoes。 或者您还在componentDidMount函数中声明self = this。然后用self instand的thisaxios

+0

头脑下降的例子吗? – feitla

1

例子:

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