React Hooks中的useEffect中的props

32

我已经开始使用react-hooks,现在有一些事情我正在努力理解。 我有这个useEffect钩子,我正在分离我的useEffect钩子,我想知道每个钩子运行的时间。

function MyComp(props) {
    useEffect(
       () => {
         fetchSomeData(props.filters)
       },[props.filters]
     )
    return (
        <div>will show my data here</div>
     )
}

只有在 props.filters 改变时,这个钩子函数才会运行吗?

还是说我必须使用 prevProps 来检查是否发生了改变?

像这样:

function MyComp(props) {
   const prevProps = useRef(props);
   useEffect(
       () => {
           if (prevProps.filters !== props.filters) {            
              fetchSomeData(props.filters)
           }
       },[props.filters]
   )
   return (
     <div>will show my data here</div>
   )
}

第二个 MyComp 中存在错误。当您使用 useRef 时,该值可以通过 current 对象访问:例如 prevProps.current官方文档 - Navid
1个回答

30
如果props.filters的值没有改变,那么React将跳过这个effect。
// This will only re-run if the value of `props.filters` changes
useEffect(() => {
  fetchSomeData(props.filters);
}, [props.filters]);

使用钩子,React 内部会自动处理,而不像使用 componentDidUpdate 的实现方式那样需要将 prevPropsnextProps 的值相互比较。

请参见通过跳过效果来优化性能


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接