Javascript 返回未定义对象的js类
我试图将一个类导入react类,但当对象在类中发生更改时,它返回未定义的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
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()
将返回的实例相同,因此它是否返回该实例与此无关。