【发布时间】:2019-03-06 15:43:47
【问题描述】:
有没有人设法在 react 16.8 中为 useState 挂钩的更新部分创建同步回调?我一直在寻找一个,以便我可以处理与 3rd 方库的同步操作,但我似乎无法根据我的需要制作一个工作。
如果有人对成功完成此任务的人有任何参考,请在此处添加。
干杯,
【问题讨论】:
标签: reactjs react-hooks
有没有人设法在 react 16.8 中为 useState 挂钩的更新部分创建同步回调?我一直在寻找一个,以便我可以处理与 3rd 方库的同步操作,但我似乎无法根据我的需要制作一个工作。
如果有人对成功完成此任务的人有任何参考,请在此处添加。
干杯,
【问题讨论】:
标签: reactjs react-hooks
使用钩子,您不再需要来自setState 函数的回调。现在,您可以使用useState 挂钩设置状态,并使用useEffect 挂钩监听其值以更新。 useEffect 钩子的可选第二个参数采用一组值来监听更改。在下面的示例中,我们只监控一个值的变化:
const Example = () => {
const [value, setValue] = useState(null);
useEffect(() => {
// do something when value changes
}, [value]);
return (
<button onClick={() => setValue('Clicked!')}>
Click Me!
</button>
);
};
阅读有关useEffect 钩子here 的更多信息。
【讨论】:
您可以使用 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>
);
};
如果您正在寻找开箱即用的解决方案,请查看 this custom hook,它的工作方式与 useState 类似,但接受回调函数作为第二个参数:
import useStateWithCallback from 'use-state-with-callback';
const SomeOtherComponent = () => {
const [count, setCount] = useStateWithCallback(0, count => {
if (count > 1) {
document.title = 'Threshold of over 1 reached.';
} else {
document.title = 'No threshold reached.';
}
});
return (
<div>
<p>{count}</p>
<button type="button" onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
};
可以通过npm install use-state-with-callback安装
如果您想同步布局更新,请改用import { useStateWithCallbackInstant } from 'use-state-with-callback';。
【讨论】: