我需要将值index
从父级传递给子级。父母和孩子都需要具有修改index
的功能。父母修改index
时,孩子无法获得更新。有什么我可以解决的吗?
家长班:
constructor(props) {
super(props);
this.state = {
index: 0
}
}
parentFunction(dir) {
this.setState({
index: 10
});
}
render() {
return(
<Child index={this.state.index}/>
);}
子类:
constructor(props) {
super(props);
this.state = {
index: this.props.index
};
}
childFunction(dir) {
this.setState({
index: this.props.index+1
});
}
render() {
return(
<div>{this.state.index}</div>
);}
最佳答案
您无需在两个类中都保留updater函数。您可以将updater函数从父级传递给子级,然后让父级处理状态更新。同样基于构造器中的props设置状态的是反模式。您应该直接在孩子中使用prop作为用例。如果需要从道具更新子状态,请确保也在componentWillReceiveProps
中执行此操作,因为constructor
仅在第一次调用时调用,并且在每个父级上都重新渲染componentWillReceiveProps
componentWillReceiveProps(newProps) {
if (newProps.index!== this.props.index) {
this.setState({
index:newProps.index
})
}
}
但是,您需要的是
家长班:
constructor(props) {
super(props);
this.state = {
index: 0
}
}
parentFunction(dir) {
this.setState({
index: 10
});
}
updaterFunction(dir) {
this.setState((prevState) => ({
index: prevState.index+1
}));
}
render() {
return(
<Child updaterFunction={(val) => this.updaterFunction(val)} index={this.state.index}/>
);}
子类:
updateProps = () => {
this.props.updaterFunction();
}
render() {
return(
<div>{this.props.index}</div>
);}