gpt4 book ai didi

javascript - 为什么会抛出这个 JS 错误?

转载 作者:行者123 更新时间:2023-11-30 14:30:34 24 4
gpt4 key购买 nike

执行下面这段代码:

function Events (props){
const clickHandler = console.log;

return (<button onClick={clickHandler}> Make an event </button>);
}

ReactDOM.render(<Events />, mountNode);

我收到此错误:Converting circular structure to JSON at JSON.stringify (<anonymous>)

代码来自 pluralsight ReactJS 类(class),当讲授该类(class)的人执行代码时,他在控制台中打印了事件触发对象,而我却收到此错误。

最佳答案

您的错误很可能是由于 jscomplete 尝试 JSON.stringify 它记录到控制台的内容。 React SyntheticEvent 具有循环结构,在其上使用 JSON.stringify 时会导致错误。

它可能适用于其他环境,但 console.log 也可能是异步的。 documentation about SynthenticEvent 中提出了这个问题:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

因此,如果您计划异步使用该事件,则可以使用以下方法:

function Events (props){
const clickHandler = (event) => {
event.persist();
console.log(event);
};

return (<button onClick={clickHandler}> Make an event </button>);
}

关于javascript - 为什么会抛出这个 JS 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51263287/

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