+
81
-

请问react中useEffect useRef useState useMemo有什么区别与不同?

请问react中useEffect useRef useState useMemo有什么区别与不同?

网友回复

+
0
-

1、useState

返回一个 state,以及更新 state 的函数。

语法:

const [n, setN] = React.useState(0); 0是n的默认值,setN是操作n的函数

在初始渲染期间,返回的状态 (state) 与传入的第一个参数 (initialState) 值相同。

setState 函数用于更新 state。它接收一个新的 state 值并将组件的一次重新渲染加入队列。

函数式更新 如果新的 state 需要通过使用先前的 state 计算得出,那么可以将函数传递给 setState。该函数将接收先前的 state,并返回一个更新后的值。下面的计数器组件示例展示了 setState 的两种用法:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
    <div id="box"></div>
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.js"></script>

    <script type="text/babel">
        const {
            useState,
            useEffect,
            useMemo,
            useRef
        } = React
        function Compont() {

            const [state,
                setState] = useState('初始值');
            return ( <div> < buttonBfwOnClick= {(e) => setState("我的值改变了")} >
                click Me! {
                    state
                } </button> < buttonBfwOnClick= {(e) => setState("bfw")} >
                click Me! {
                    state
                } </button> </div>
            )

        }
        ReactDOM.render( < Compont/>, document.getElementById('box'))
    </script>
</body>
</html>

2、useEffect

监听第二个参数[]的state的变化,执行第一个参数

useEffect第二个参数为空数组的时候,相当于componentDidMount

useEffect在第一个参数(函数主体里return相当于componentWillUnmount)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

</head>
<body>
    <div id="box"></div>
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.js"></script>

    <script type="text/babel">
        const {
            useState,
            useEffect,
            useMemo,
            useRef
        } = React
        function Compont() {


          
                const [time,
                    settime] = useState(Date());
                let timer = 0;
                useEffect(() => {
                    timer = setInterval(() => {
                        settime(Date())
                    }, 1000);
                    return ()=> {
                        clearInterval(timer)
                    }
                }, []);
                return time
           

        }
        ReactDOM.render( <Compont/>, document.getElementById('box'))
    </script>
</body>
</html>

如果在第一个参数里存在定时器记得在return的时候清除掉,不清除掉会抱错 devScripts.js:5035 Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. 函数名字首字母记得大写否则会报这个错 “useEffect” is called in function “dateTime” that is neither a React function component nor a custom React Hook useEffect监听变量的时候,初始值也会监听到,所以,做个判断,可以减少一次不必要的渲染
useEffect(() => {
  if(state){
   console.log(state,'state')
  }
}, [state])

监听多个变量的时候,任意一个变量发生变化都会执行

3、useRef

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。 一个常见的用例便是命令式地访问子组件:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

</head>
<body>
  <div id="box"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.js"></script>
  
  <script type="text/babel">
    const {useRef} = React
    function Compont() {
      const username = useRef()
      const password = useRef()
      const handleClick = () => {
        console.log('用户名:' + username.current.value)
        console.log('密码:' + password.current.value)
      }
      return(
        <div>
          用户名:<input type="text" ref={username} /> <br/>
          密码:<input type="password" ref={password} /> <br/>
          <buttonBfwOnClick={handleClick}>点击登入</button>
        </div>
      )
    }
    ReactDOM.render( <Compont/>, document.getElementById('box'))
  </script>
</body>
</html>

4、useMemo

大概就是使用最新的数据,返回新的Dom节点 使用的时候就像state一样使用 {变量名} 就可以了 好处:

可以避免不必要的重复渲染,也不怕拿不到最新的数据去渲染

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

</head>
<body>
  <div id="box"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
  <script src="https://cdn.bootcss.com/babel-standalone/7.0.0-beta.3/babel.js"></script>
  
  <script type="text/babel">
    const  { useState, useEffect,useMemo,useRef }  = React
    function App() {
  const [name, setName] = useState('名称')
  const [content,setContent] = useState('内容')
  return (
       <div>
        <buttonBfwOnClick={() => setName(new Date().getTime())}>name</button>
        <buttonBfwOnClick={() => setContent(new Date().getTime())}>content</button>
        <Button name={name}>{content}</Button> </div>
     
  )
}
function Button({ name, children }) {
  function changeName(name) {
    console.log('11')
    return name + '改变name的方法'
  }

const otherName =  useMemo(()=>changeName(name),[name])
  return ( <p>
        <div>{otherName}</div>
        <div>{children}</div> </p>

  )
}


     
    ReactDOM.render( <App/>, document.getElementById('box'))
  </script>
</body>
</html>

我知道答案,我要回答