gpt4 book ai didi

javascript - react 事件处理程序中的错误被多次触发

转载 作者:行者123 更新时间:2023-12-01 02:23:17 26 4
gpt4 key购买 nike

如果错误发生在 react 事件处理程序中(在本例中为 onChange),它会在控制台中显示两次。这是对的吗?也许我做错了什么?

onChange 处理程序被调用一次。

我要在我的页面上设置监控,并且不希望出现重复的错误。

在 React v16 中测试。

https://codesandbox.io/s/480y71xo00

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

class App extends React.Component {
constructor(props){
super(props);
this.state = { text: '' };
}

onChange(event){
console.log('Call unknown function once');
//!!!
what();

this.setState({
text: event.target.value
});
}

render(){
const {text} = this.state;

return (
<div>
<Hello name="CodeSandbox" />
<h2>Start editing to see some magic happen {'\u2728'}</h2>
<input type="text" value={text} onChange={this.onChange.bind(this)}/>
</div>
);
}
}

render(<App />, document.getElementById('root'));

如果您在输入中键入内容:

在 Chrome 中 enter image description here

但是在 Safari 中错误看起来像这样: enter image description here

最佳答案

此行为是有意为之的,https://github.com/facebook/react/issues/10384 对此进行了解释。并在这里讨论:https://github.com/facebook/react/issues/10474

以下是 Dan Abramov 的解释:

For context, the reason it happens is because we intentionally let the browser interpret an error as uncaught before we rethrow. The justification is discussed in #10474.

If you follow the advice in the error and add an error boundary (which you should!), you will only see the error once. So that's not a huge problem in day-to-day workflow. In fact it nudges people to add error boundaries which is nice.

Another justification for this is that if you accidentally swallow an error we still print it once. That alone makes this worth it IMO. We’ve had hundreds of comments and dozens of issues caused by people swallowing their own errors, and the fact that we will print them at least once now seems like enough benefit to compensate for printing them twice when they’re uncaught, un-swallowed, and don’t have a boundary.

关于javascript - react 事件处理程序中的错误被多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com