js类返回未定义的对象

时间:2019-04-23 03:54:10

标签: javascript reactjs

我正在尝试将一个类导入一个react类,但是当对象在该类中更改时,它返回的是不确定的。

class Test {
  constructor(){
    this.obj = {}
  }

  testFunc(){
    this.obj.one = 'two'
    // this returns the value
    console.log(this.obj.one)
  }
}

class App extends Component{
  constructor(){
    super()
    this.testClass = new Test()
  }

  componentDidMount(){
    this.testClass.testFunc()
    // this returns undefined
    console.log(this.testClass.obj.one)
  }
}

3 个答案:

答案 0 :(得分:0)

我认为您在应用程序组件上缺少渲染器

  constructor(){
    this.obj = {};
  }

  testFunc() {
    this.obj.one = 'two';
    // this returns the value
    console.log(this.obj.one);
  }
}

class App extends React.Component{
  constructor(){
    super()
    this.testClass = new Test();
  }

  componentDidMount(){
    this.testClass.testFunc();
    console.log('value =>', this.testClass.obj.one);
  }

  render() {
    return <div />;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

答案 1 :(得分:0)

I have done few tweaks. Your  code is working fine and returning the expected results.

您可以检查小提琴:

JS Fiddle

答案 2 :(得分:-1)

我认为,如果您想使用console.log(this.testClass.obj.one),则需要在 this 函数中返回 testFunc() 关键工作

相关问题