hooks

青丘白狐發表於2020-12-15

useState

const [count, setCount] = useState(0);

const [person, setPerson] = React.useState({name: '張三瘋', age: 18,sex:"女"})
const [person, setPerson] = React.useState(() => ({name: '張三瘋', age: 18,sex:"女"}))


setCount(5);

  setPerson({
     ...person, //拷貝之前的所有屬性
     age:person.age+1,
     name: '張四瘋' //這裡的name覆蓋之前的name
 })

useEffect

當資料發生變化後,渲染到元件上,元件渲染完畢後,就會呼叫useEffect(函式式元件)

import React,{useState,useEffect} from 'react';

function App() {
  const [count,setCount] = useState(0);
  
  useEffect(()=>{
      console.log("userEffect");
      document.title = count;
  });

  return (
    <div className="App">
      <p>{count}</p>
      <input type="button" value="測試" onClick={()=>{setCount(count+1)}} />
    </div>
  );
}

相關文章