Hook新特性(一)

基础Hook

1、useState

const [state, setState] = useState(initialState);
//返回一个state变量,指为initialState,setState函数用来设置state的值 setState(1)

2、useEffect

const [count, setCount] = useState(1)
useEffect(()=>{
    console.log(count)
})

useEffect相当于三个生命周期函数:componentDidMount、componentDidUpdate、componentWillUnMount。

useEffect接收两个参数,第二个参数传入空数组,相当于生命周期componentDidMount、componentWillUnMount,只执行一次。没有参数相当于componentDidMount、componentDidUpdate,传入[count]只监听count的变化,发生变化才会触发第一个参数中的函数。在第一个参数传入的函数中retrun ()=>{}相当于才componentWillUnMount。

3、useContext

const MyContext = React.createContext();
function MainPage(){
  return (
    <div>
      <MyContext.provider value="hello world">
        <ChildPage />
      </MyContext.provider>
    </div>
  )
}

function ChildPage(){
  return(
    <div>
      <p>{ useContext(MyContext) }</p>
    </div>
  )
}

 

posted @ 2020-07-17 14:57  朝思暮想的虫  阅读(430)  评论(0编辑  收藏  举报