【问题标题】:React this is undefined反应这是未定义的
【发布时间】:2016-07-07 06:06:34
【问题描述】:

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

【问题讨论】:

    标签: reactjs this


    【解决方案1】:

    可能它没有绑定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) )
    

    【讨论】:

    • 我们应该删除// 'this' isn't working 评论吗?
    【解决方案2】:

    您可以将this 绑定到这些函数中。 或者你也在componentDidMount函数中声明self = this。然后在axios 中使用self 代替this

    其他方式:使用箭头函数

    【讨论】:

      【解决方案3】:

      例子:

      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

      【讨论】:

        猜你喜欢
        • 2020-07-13
        • 1970-01-01
        • 2017-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-18
        • 2018-07-06
        • 1970-01-01
        相关资源
        最近更新 更多