react学习之react-hooks

简单使用

  1. useState
    useState 是最简单的一个 hook
    唯一需要注意的是不要尝试在循环或者条件等不稳定的代码结构中编写
import React,{ useState } from 'react'
export default function Example() {
  const [name, setName] = useState('swj')
  return (
    <div>
      {name}
      <button onClick={()=>setName('yxs')}>更改</button>
    </div>
  )
}

  1. useEffect
  useEffect(()=>{})
  相当于 componentDidMount + componentDidUpdate
  在useEFFECT中return函数表示componentWillUnmount

例子

import React,{ useState,useEffect } from 'react'
import { BrowserRouter as Router,Route,Link } from 'react-router-dom'
function Index(){
  useEffect(()=>{
    console.log('进入');
    return ()=>{
      console.log('离开');
    }
  })
  return <h3>首页</h3>
}
function List(){
  return <h3>列表</h3>
}
export default function Example2() {
  return (
    <div>
      <Router>
        <ul>
          <li><Link to="/">首页</Link></li>
          <li><Link to="/list">列表</Link></li>
        </ul>
        <Route path="/" exact component={Index}></Route>
        <Route path="/list" exact component={List}></Route>
      </Router>
    </div>
  )
}
  1. useContext
import React,{createContext,useContext,useState} from 'react'
// 创建context
const CountContext = createContext()
// 子组件
function Counter(){
  let count = useContext(CountContext)
  return <h1>{count}</h1>
}

export default function Example3() {
  const [count,setCount] = useState(0)
  return (
    <div>
      <button onClick={()=>setCount(count+1)}>+++++++</button>
      <CountContext.Provider value={count}>
        <Counter></Counter>
      </CountContext.Provider>
    </div>
  )
}
  1. useReducer
import React,{ useReducer } from 'react'

export default function Example4() {
  const [count,dispatch] = useReducer((state,action)=>{
    switch (action.type) {
      case 'add':
        return state+1
    case 'sub':
      return state-1
      default:
        return state
    }
  },0)
  return (
    <div>
      <h3>{count}</h3>
      <button onClick={()=>{dispatch({type:'add'})}}>+</button>
      <button onClick={()=>{dispatch({type:'sub'})}}>-</button>
    </div>
  )
}
  1. useMemo
  2. useRef
import React,{ useRef } from 'react'
export default function Example5() {
  const inputE1 = useRef(null)
  const btnClick = ()=> {
    inputE1.current.value = 'swj'
    console.log(inputE1);
  }
  return (
    <div>
      <input ref={inputE1} type="text"></input>
      <button onClick={btnClick}>点击</button>
    </div>
  )
}

你可能感兴趣的:(React,react)