1. 程式人生 > 其它 >如何React的函式式元件中使用useContext和useReducer來簡單替代redux

如何React的函式式元件中使用useContext和useReducer來簡單替代redux

1. 首先是user.jsx

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

const UserContext = createContext()
const user = {
    username: '',
    email: ''
}

export const UPDATE_USER = 'UPDATE_USER'
export const UPDATE_USERNAME = 'UPDATE_USERNAME'
export const UPDATE_EMAIL = 'UPDATE_UEMAIL'
export const RESET_USER = 'RESET_USER'

const userReducer = (state=user, action={type: '', payload: {}})=>{
    switch(action.type){
        case UPDATE_USER:
            return {...action.payload}
        case UPDATE_USERNAME:
            return {...state, username: action.payload}
        case UPDATE_EMAIL:
            return {...state, email: action.payload}
        case RESET_USER:
            return {...user}
        default:
            return state

    }
}

export default function UserContext(props) {
    const [state, dispatch] = useReducer(user, userReducer)

    return (
        <UserContext.Provider value={{state, dispatch}}>
            {props.children}
        </UserContext.Provider>
    )
}

2. 然後是App.jsx中引入

import React from 'react'
import UserContextWrapper from './user'

export default function App() {

  return (
    <UserContextWrapper>
        <div>App</div>
    </UserContextWrapper>
  )
}

3. 最後是child.jsx中使用

import React, { useContext } from 'react'
import { UPDATE_EMAIL, UserContext } from './user'


export default function Child() {
    const userContext = useContext(UserContext)
    const {username} = userContext.state

    return (
        <div>
            <div>username:{username}</div>
            <span>email: </span>
            <input type="text" onChange={(value)=>userContext.dispatch(UPDATE_EMAIL, value)} />
        </div>
    )
}