美文网首页
useReducer, useContext

useReducer, useContext

作者: penelope_2bad | 来源:发表于2020-06-21 17:34 被阅读0次

    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

    相关文章

      网友评论

          本文标题:useReducer, useContext

          本文链接:https://www.haomeiwen.com/subject/idsaxktx.html