问题描述
您可以使用 useEffect/useLayoutEffect 来实现:
const SomeComponent = () => {
const [count, setCount] = React.useState(0)
React.useEffect(() => {
if (count > 1) {
document.title = 'Threshold of over 1 reached.';
} else {
document.title = 'No threshold reached.';
}
}, [count]);
return (
<div>
<p>{count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
如果要防止回调在第一次渲染时运行,请调整以前的版本:
const SomeComponent = () => {
const [count, setCount] = React.useState(0)
const didMount = React.useRef(false);
React.useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
if (count > 1) {
document.title = 'Threshold of over 1 reached.';
} else {
document.title = 'No threshold reached.';
}
}, [count]);
return (
<div>
<p>{count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
更多关于它在这里。
解决方法
我正在使用带有钩子的功能组件。我需要从孩子更新父母的状态。我在 Parent 中使用了一个 prop 函数。一切正常,除了我的 prop
函数正在获取以前的状态而不是当前状态。我的 prop 函数在 useState 钩子设置当前状态之前执行。我怎样才能等待我的回调函数在
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>);
}