Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 返回未定义对象的js类_Javascript_Reactjs - Fatal编程技术网

Javascript 返回未定义对象的js类

Javascript 返回未定义对象的js类,javascript,reactjs,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(){ supe

我试图将一个类导入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)
  }
}

我认为您缺少应用程序组件上的渲染:

  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')
);
constructor(){
this.obj={};
}
testFunc(){
this.obj.one='two';
//这将返回值
console.log(this.obj.one);
}
}
类应用程序扩展了React.Component{
构造函数(){
超级()
this.testClass=new Test();
}
componentDidMount(){
this.testClass.testFunc();
log('value=>',this.testClass.obj.one);
}
render(){
返回;
}
}
ReactDOM.render(
,
document.getElementById('root'))
);

我想,如果你想使用
console.log(this.testClass.obj.one)
你需要在
testFunc()函数中返回
这个

I have done few tweaks. Your  code is working fine and returning the expected results.
您可以检查小提琴:


你确定吗?你是说
this.testClass.testFunc()
输出
two
但是
console.log(this.testClass.obj.one)
输出
未定义的
?因为,从代码中删除reactjs内容,效果很好,可能您在控制台输出上看不到
2
,这意味着
2
被发送到控制台两次,而
未定义的
来自其他内容。。。试试
console.log('in componentDidMount',this.testClass.obj.one)
ok,所以如果我这样做
console.log(this.testClass.obj)
chrome控制台将只显示
{}
,但是如果我在测试类构造函数
this.obj={Test Test:}
中设置一个值,它将显示
{Test Test:}Test}
在chrome控制台中,是否可以将
testFunc
方法绑定到
Test
类?尝试将此行添加到构造函数中:
this.testFunc=this.testFunc.bind(this)
听起来像是一个典型的异步问题。您正在访问设置前的属性。您的实际代码必须不同。请贴一个更好的例子。但是表达式
this.testClass.obj.one
中的
this
很可能是重复的。如果从
testFunc
返回
this
,则会得到
Test
的一个实例。由于
App
已经为
this.testClass
分配了一个
Test
实例,并且该实例与
this.testClass.testFunc()
将返回的实例相同,因此它是否返回该实例与此无关。