引用“ this”并尝试将其存储到变量中会产生未定义的但已在DevTools中定义

时间:2018-07-24 02:27:09

标签: javascript reactjs this jsx

我在我的React应用程序中看到关于绑定的“ this”的一些奇怪行为-我有一个函数是名为“ App”的组件的一部分。它在单独的文件中,我已将“ this”命令绑定到主文件中。

我注意到在函数本身中,“ this”的行为是不一致的。正如您在下面的代码示例中看到的那样,当在条件之前引用“ this”关于前几个变量时,我看到它在调试器中正确绑定,但是当我引用绑定变量或“ this”语句时在条件我得到未定义的值。据我了解,条件函数不会像函数那样更改“ this”的范围,因此问题出在哪里没有意义。

编辑:为了清楚起见,更新了确切的代码

Undo.js:

import React from 'react';
import {App} from 'react';

export default function onUndoAction(event){

    //Need to prevent error throw on undefined 

  let undoArrLength = this.state.undo.length-1;
      let undoType = this.state.undo[undoArrLength].type;


  //undoType.check is only present in undo events with cell value entries

  let undoStateCopyOut = this.state;

  if (undoType == "cell"){

    let undoStateCopy = this.state;


    //loop back to prior similar undo action

    for(let i = undoStateCopy.length-2; i >= 0; i--){
      if(undoStateCopy[i].type == "cell"){
        //Set this value as the new value 
        this.setState({gridState: undoStateCopy[i]})
        //then pop the prior value
        /*  Need to integrate this. 
        let addition = newUndo.pop();
        newRedo.push();
        let newRedo = redoStateCopy.splice(redoStateCopy.length-1,0, newUndo);
        this.setState({undo: newUndo});
        this.setState({redo: newRedo});
        */
        break;
      }
    }

  }
    ... additional code

Main.js

...

      onUndoAction(){
        onUndoAction;
      }


...skipping to render method

render(){
        return (
          <div>
          <table>
          <tbody onLoad = {this.broadcast()}>  
            {this.MainTableGet()}
          </tbody>
          </table>
          <ButtonMenu onRow = {this.onRowButton} onCol = {this.onColumnButton} undo ={ (e) => this.onUndoAction(e)} redo = {this.onRedoAction} reset = {this.onResetAction} />
          </div>

        );
      }

一些注意事项:

我不确定这是否是React的特质-我知道您不能在JSX中使用条件,从技术上讲,这是在render函数中引用的函数,但是我无法想象您完全不能在React中使用任何if语句。

1 个答案:

答案 0 :(得分:0)

您可以使用es6方法来更新以下代码:

export const exportedVar = () => {
let stateCheck = this.state.stateCheckValue  //successfully pulls in the values of "this"

let thisState = this;  //in console, reads as thisState = App {props: {...}, state:{...} ...}

if (stateCheck == "foo") {


    let someVariable = thisState //Undefined!!

    //still undefined even if I set:
    // let thisState = this.state;


    ...