美文网首页
useState&useEffect初始化变化被监听

useState&useEffect初始化变化被监听

作者: 我是Msorry | 来源:发表于2021-01-09 09:57 被阅读0次

    状态1

    Line 20:8: React Hook useEffect has a missing dependency: 'updateCount'. Either include it or remove the dependency array. You can also do a functional update 'setUpdateCount(u => ...)' if you only need 'updateCount' in the 'setUpdateCount' call react-hooks/exhaustive-deps

    useEffect(
        () => {
          setUpdateCount(updateCount + 1)
        }, [n])
    
    改成
    useEffect(
        () => {
          setUpdateCount(u => u + 1)
        }, [n])
    

    状态2

    React Hook "useEffect" is called in function "x" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
    自定义的函数组件必须以use开头

    const useX =()=>{
        const [updateCount, setUpdateCount] = useState(0)
        useEffect(
          () => {
            setUpdateCount(u => u + 1)
          }, [n])
      }
      useX()
    

    状态3

    'updateCount' is not defined no-undef
    把updateCount变成函数的返回值,返回给外面

    const useX = () => {
        const [updateCount, setUpdateCount] = useState(0)
        useEffect(
          () => {
            setUpdateCount(u => u + 1)
          }, [n])
        return {updateCount}
      }
      const {updateCount} = useX()
    

    状态4

    React Hook useEffect has an unnecessary dependency: 'n'. Either exclude it or remove the dependency array. Outer scope values like 'n' aren't valid dependencies because mutating them doesn't re-render the component react-hooks/exhaustive-deps
    n不是在useX这个函数内部定义的,不是有效的依赖
    把n作为参数传进useX

      const useX = (n) => {
        const [updateCount, setUpdateCount] = useState(0)
        useEffect(
          () => {
            setUpdateCount(u => u + 1)
          }, [n])
        return {updateCount}
      }
      const {updateCount} = useX(n)
    

    状态5

    消除所有的警告,功能符合预期,继续重构

    状态6

    把useX重构成useUpdate,所有的都是外部传进来的

    React Hook useEffect was passed a dependency list that is not an array literal. This means we can't statically verify whether you've passed the correct dependencies react-hooks/exhaustive-deps
    React Hook useEffect has a missing dependency: 'fn'. Either include it or remove the dependency array. If 'fn' changes too often, find the parent component that defines it and wrap that definition in useCallback react-hooks/exhaustive-deps
    直接传递数组,数组长度可能非常大,不能静态验证,这样做不安全,应该传递一个数组项
    [...array]这样写也不安全
    用了fn,但缺少fn的依赖项

    状态7

    重构完成

    总结

    消除警告

    React里,有警告就要去解决
    先看警告对应的行数,再看警告内容

    相关文章

      网友评论

          本文标题:useState&useEffect初始化变化被监听

          本文链接:https://www.haomeiwen.com/subject/cfudrktx.html