我需要创建一个功能性的反应组件,每次发生特定事件时自动更新内部数据。
我编写了下面的代码,但是每次调用回调时,都会重新渲染组件,并且将变量myArray
设置为空数组,而不是填充回调中的所有内容。
我究竟做错了什么?我应该使用什么方法?
// event emulation
function onEventEmulator(callback, interval = 1000) {
setInterval(() => callback('content'), interval);
}
function PollingComponent(props) {
const [myArray, setMyArray] = useState([]);
useEffect(() => {
onEventEmulator(content => {
setMyArray([...myArray, content]);
});
}, []); // with or without passing the empty array as second param, result does not change.
return <ul>
<li>Callback</li>
<li>{myArray.length}</li>
</ul>;
}