我正在使用带有挂钩的功能组件。我需要从孩子那里更新父母的状态,并且我正在使用父母的道具功能。一切正常,除了我的prop函数获取最后一个状态,而不是当前状态,因为在useState钩子设置当前状态之前执行我的prop函数。我该如何等待useState调用之后执行我的回调函数。我正在寻找类似我们正在使用setState(state,callback)作为第二个参数的东西。下面是相同的代码片段。
function Parent() {
const [Name, setName] = useState("");
getChildChange = getChildChange.bind(this);
function getChildChange(value) {
setName(value);
}
return <div> {Name} :
<Child getChildChange={getChildChange} ></Child>
</div>
}
function Child(props) {
const [Name, setName] = useState("");
handleChange = handleChange.bind(this);
function handleChange(ele) {
setName(ele.target.value);
props.getChildChange(collectState());
}
function collectState() {
return Name;
}
return (<div>
<input onChange={handleChange} value={Name}></input>
</div>);
}
Run Code Online (Sandbox Code Playgroud)