我在自定义的react挂钩中获得了以下代码,该代码可能会根据先前的状态数据引发错误。
Please enter your username
['All Users', 'Default', 'Default User', 'desktop.ini', 'John', 'maxwe', 'Public'] #print(users)
>>> maxwe #me inputting my username
1 #prints that 'maxwe' shows up once
Sorry! That username was not found, try again #but it returns false when 'if' function is used
Or press C to create an account
但是当我执行以下操作时:
const [data, setData] = useState({});
const handleSomething = () => {
setData((oldData) => {
if (/* some condition based on oldData */) {
throw new Error('Bad');
}
// Other code
return newData;
});
}
我的try {
handleSomething()
} catch (err) {
console.log('There was an error');
}
块未输入,错误仍然出现。从我的猜测看来,React似乎正在提高错误,然后崩溃了而不是让我这样做。我如何避免这样的事情?
答案 0 :(得分:0)
如果您使用的是React> =版本16:请查看生命周期方法:componentDidCatch()和静态getDerivedStateFromError()...