简体   繁体   English

Javascript 中的空方括号?

[英]Empty Square Brackets in Javascript?

I came across this code in https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks :我在https://upmostly.com/tutorials/setinterval-in-react-components-using-hooks中遇到了这段代码:

useEffect(() => {
  const interval = setInterval(() => {
    console.log('This will run every second!');
  }, 1000);
  return () => clearInterval(interval);
}, []);

I am curious what the square brackets [] at the end do?我很好奇最后的方括号[]是做什么的? According to this site https://reactjs.org/docs/hooks-effect.html , we can use useEffect() without them.根据这个站点https://reactjs.org/docs/hooks-effect.html ,我们可以在没有它们的情况下使用 useEffect() 。

We put an empty [] , if we want the code inside useEffect to run only once.如果我们希望 useEffect 中的代码只运行一次,我们放置一个空的[] Without empty [] , the code inside the useEffect will run on every render如果没有空[] ,useEffect 中的代码将在每次渲染时运行

See the documentation :请参阅文档

We don't need to create a new subscription on every update, only if the source prop has changed.我们不需要在每次更新时都创建一个新订阅,只要源属性发生了变化。

... ...

pass a second argument to useEffect that is the array of values that the effect depends on.将第二个参数传递给 useEffect,它是效果所依赖的值数组。

... ...

If you pass an empty array ([]), the props and state inside the effect will always have their initial values.如果传递一个空数组([]),则效果中的道具和 state 将始终具有其初始值。 While passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model, there are usually better solutions to avoid re-running effects too often.虽然传递 [] 作为第二个参数更接近于熟悉的 componentDidMount 和 componentWillUnmount mental model,但通常有更好的解决方案来避免过于频繁地重新运行效果。

This code is used to mimic the properties of componentDidMount() in class based components.此代码用于模拟基于 class 的组件中 componentDidMount() 的属性。 That is, it will only get invoked when the component is mounted.也就是说,它只会在组件被挂载时被调用。

If we don't specify an empty array ( [] ) as the second argument of the useEffect hook, the hook will exhibit the behaviour of an componentDidUpdate.如果我们不指定一个空数组 ( [] ) 作为 useEffect 钩子的第二个参数,那么该钩子将表现出 componentDidUpdate 的行为。 It means every time some prop's value changes, the useEffect hook will be triggered.这意味着每次某个 prop 的值发生变化时,都会触发 useEffect 挂钩。

The second array argument allows you to specify which prop trigger the userEffect() callback when their value changes第二个数组参数允许您指定哪个道具在其值更改时触发 userEffect() 回调

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM