鍍金池/ 問答/HTML/ 在react項(xiàng)目中,失去this指針,為什么?

在react項(xiàng)目中,失去this指針,為什么?

圖片描述

import React from 'react';
import Red from './images/red.png'
import Yellow from './images/yellow.png'
import Green from './images/blue.png'

class Warn extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataHeader:  '',
            dataContent: ''
        }
        this.tableTimer = null;
    }

    /**
     * 動態(tài)創(chuàng)建表格
     * @private
     */
    _createTable() {

        const self = this; // 指向本對象的指針

        console.log('=================創(chuàng)建表格開始=================');
        console.log(self);
        console.log('=================創(chuàng)建表格結(jié)束=================');



        var warning = document.getElementsByClassName('warning')[0];

        // 開始輪播
        self.tableTimer = self._setInterval(self._replaceTable, 5000, this.state.dataContent);

    }

    /**
     * 替換表格內(nèi)容
     */
    _replaceTable(content){


        const self = this;

        console.log('=================replaceTable=================');
        console.log(self);
        console.log('=================replaceTable=================');

    }

    /**
     * 可帶參數(shù)的定時去
     * @param callback
     * @param timeout
     * @param param
     * @private
     */
    _setInterval(callback,timeout,param){


        const self = this;

        console.log(self)

        var _sto = setInterval;

        // slice() 方法可從已有的數(shù)組中返回選定的元素
        // arrayObject.slice(start,end)
        var args = Array.prototype.slice.call(arguments,2);

        console.log(args)

        var _cb = function()
        {
            callback.apply(null,args);
        }

        var stoTimer = _sto(_cb,timeout);


        return stoTimer;
    }

    componentDidMount() {
        this._createTable();
    }

    // 組件接收到新的props時調(diào)用,并將其作為參數(shù)nextProps使用
    componentWillReceiveProps(nextProps) { // 接收新的參數(shù)
        var dataFlowPercentage01 = []

    }

    componentDidUpdate() {
        console.log('表格正式更新')
        const self = this;

    }


    render() {
        let self = this;

        var divStyle = {
            width: 632,
            height: 210,
            position: 'absolute',
            left: 235,
            top:120,
            color: '#D8D8D8',
            fontSize: 50
            //backgroundColor: 'yellow'
        }


        return (
            <div className={'warning'} style={divStyle}>
                這個
            </div>
        );

    }
}

export default Warn;
回答
編輯回答
奧特蛋

下面這段代碼將_setInterval的回調(diào)函數(shù)的this都指向了null。

另外如果只修改下面這段代碼,this的會指向undefined。根本原因是回調(diào)函數(shù)運(yùn)行環(huán)境的this并不指向當(dāng)前組件。解決方法是在構(gòu)造函數(shù)中用bind綁定方法,或者使用箭頭函數(shù)

var _cb = function()
        {
            callback.apply(null,args);
        }
//1.bind綁定
constructor() {
  // ...
  this.method = this.method.bind(this)
}

//2.箭頭函數(shù)
class XXX extend Component {
  constructor() {}

  method = () => {
    // ...
  }

}
2018年1月16日 12:01
編輯回答
厭惡我
// 將你的_createTable方法重寫如下編寫
_createTable(){
    const self = this; // 指向本對象的指針
    console.log('=================創(chuàng)建表格開始=================');
    console.log(self);
    console.log('=================創(chuàng)建表格結(jié)束=================');
    var warning = document.getElementsByClassName('warning')[0];
    // 開始輪播 //TODO 這里代碼重構(gòu)
    //self.tableTimer = self._setInterval(self._replaceTable, 5000, this.state.dataContent);
    self.tableTimer = self._setInterval(()=>{
        self._replaceTable();
    },5000,this.state.dataContent)
}
2017年11月26日 03:28