[英]Using setInterval and updating state inside useEffect how to prevent other component to re-render
I have 2 components List.js and Counter.js.我有 2 个组件 List.js 和 Counter.js。 Under App.js after the DOM render I need the setInterval to trigger each second showing the incremental count.
在 DOM 渲染后的 App.js 下,我需要 setInterval 来触发每秒显示增量计数。 Also there is a list that should only trigger when manually submitted.
还有一个列表应该只在手动提交时触发。
App.js应用程序.js
export default function App() {
const addtolist = useRef();
const [item, setItem] = useState([]);
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
const submitHandler = () => {
setItem((item) => [...item, addtolist.current.value]);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input type="text" name="addtolist" ref={addtolist} />
<button onClick={submitHandler}>Submit</button>
<Counter count={count} />
<List data={item} />
</div>
);
}
The problem above is each time the count is set the List component also renders.上面的问题是每次设置计数时,列表组件也会呈现。 Need to prevent that from re-rendering.
需要防止重新渲染。 The List component should only render when item state is set.
列表组件应仅在设置项目state 时呈现。
Updating the state of a component will trigger a re-render for this component.更新组件的 state 将触发该组件的重新渲染。 And by default, when a component re-render its children will also re-render.
默认情况下,当一个组件重新渲染时,它的子组件也会重新渲染。
To prevent <List>
from re-rendering when count
changes, simply move your useEffect
and count
state in <Counter>
or on a separate component wrapping <Counter>
:要防止
<List>
在count
更改时重新呈现,只需移动您的useEffect
并在<Counter>
中或在包装<Counter>
的单独组件上count
state :
const CounterContainer = () => {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setInterval(() => {
setCount((count) => count + 1);
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return <Counter count={count} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.