javascript - 在使用 React 钩子验证新状态时修改上游状态
问题描述
我正在尝试使用与此类似的 React 钩子:
function MyComponent({ setError }) {
const [total, setTotal] = useState('');
// ...
useEffect(() => {
setTotal(oldTotal => {
const newTotal = oldTotal + inputValue;
// some validation step
if (newTotal.length % 2 !== 0) {
setError(`${inputValue} was wrong`);
return oldTotal;
}
return newTotal;
});
}, [inputValue, setError]); // I don't want this to re-evaluate when `total` changes.
// ...
}
但是,setError
触发另一个useState
回调会触发另一个重新渲染,并且 React 不喜欢在状态转换期间重新渲染。
我应该如何构造这段代码,以便setError
在它应该被调用时被调用?
解决方案
推荐阅读
- python - 从满足条件的 df 中提取任意 2 行 - Pandas
- python-2.7 - 如何使用 uArm Pro Python 库
- c++ - 显式特化源文件中的类模板
- javascript - reactjs有功能重复运行
- pyqt5 - 如何在 Raspberry pi 上的 PyQt5 中使窗口透明?
- reactjs - 在关闭反应时清除模式的特定内容
- arrays - 没有参考周期的快速方法数组
- ios - 构建未显示在 iTunes Connect 上
- ruby - Docker hub 的官方 ruby 镜像是如何创建的?
- javascript - 在 WebGL 中使用三角形网格进行光线追踪,使用 3k+ 个三角形失败