我不确定如何在标题上准确地表达出来,因为问题在我的场景中太具体了,但无论如何基本上我有两个类似于下面的外部类:
class Config {
public level: number = 1; //this is a sample state I want to pass
//sets level
public setLevel(level: number){
this.level = level;
}
}
//wrapper class that uses Config class as a property
class Manager {
public config: Config = new Config();
//invokes Config.setLevel() here, but wrapped
public nextLevel(level: number){
this.config.setLevel(level)
}
}
然后我的 react 组件是:
//here is my parent component using Manager
class ParentComp extends React.Component{
public mngr: Manager = new Manager(); //uses Manager as a property
constructor(props: any){
super(props);
this.state = { config: this.mngr.config }; //adds the Manager instance's property as a state
}
public render(){
//passes the state to a child component
return(
)
}
//this is where I simulate changing the level property using the external class(es)
componentDidMount(){
setTimeout(()=>{
this.mngr.nextLevel(2); //invoke external class method that changes the source object
console.log('1 sec has passed and a new level has been set.')
}, 1000)
}
}
class ChildComp extends React.Component{
constructor(props: any){
super(props);
this.state = {level: props.level} //uses the prop to the child's state
}
}
基于 React 开发工具,
ParentComp
上的
componentDidMount
确实会更改 ParentComp.config.level
,但不会更改 ChildComp.level
.
为什么以及该怎么做?我有 Vue 背景,通常 Vue 会自动处理这些事情。我不明白为什么它不适用于 React。
您没有在实现中使用 setState
属性,这就是没有更改的原因。
关于javascript - react : passing parent state to child when the parent state is sourced and modified from external classes acting as a property in the parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57848479/
Tôi là một lập trình viên xuất sắc, rất giỏi!