useReducer, useContext

2020-06-21  本文已影响0人  penelope_2bad

1. useReducer的实现

import React, {useReducer} from 'react'

const reducer = (state, action) => {
  switch (action.type) {
    case 'ADD':
      return state + 1
    case 'SUB':
      return state - 1
    default: return state
  }
}

const Child = () => {
  const [count, dispatch] = useReducer(reducer, 10)

  return (
    <div>
      child:
      count: {count}
      <button onClick={() => dispatch({type: 'ADD'})}>+1</button>
      <button onClick={() => dispatch({type: 'SUB'})}>-1</button>
    </div>
  )
}

const Parent = () => {
  return <div>parent:<Child /></div>
}

function App() {
  const [count, dispatch] = useReducer(reducer, 20)

  return (
    <div className="App">
      <Parent />
      <Child />
    </div>

  )
}

export default App

2. 用useReducer实现useState

const  useState = (initState) => {
  const [state, dispatch] = useReducer((state, action) => (state || initState), initState))
  return [state, dispatch]
}

3. 结合useContext实现全局状态管理

import React, {useReducer, useContext} from 'react'

const Ctx = React.createContext(null)

const reducer = (state, action) => {
  switch (action.type) {
    case 'ADD':
      return state + 1
    case 'SUB':
      return state - 1
    default: return state
  }
}

const Child = () => {
  const [count, dispatch] = useContext(Ctx)

  return (
    <div>
      child:
      count: {count}
      <button onClick={() => dispatch({type: 'ADD'})}>+1</button>
      <button onClick={() => dispatch({type: 'SUB'})}>-1</button>
    </div>
  )
}

const Parent = () => {
  const [count] = useContext(Ctx)
  return <div>parent:{count}</div>
}

function App() {
  const [count, dispatch] = useReducer(reducer, 20)

  return (
    <Ctx.Provider value={[count, dispatch]}>
      <div className="App">
        <Parent />
        <Child />
      </div>
    </Ctx.Provider>

  )
}

export default App

使用场景: 如果偶尔组件之间需要传递状态,并且不希望通过props进行层层透传,可以用useReducer,useContext解决这样的问题。
但是当状态变得特别复杂的时候,建议使用redux

上一篇下一篇

猜你喜欢

热点阅读