0

我正在使用 context api 进行 crud 操作并使用 reducer。我从 api 获取数据并将其存储为初始值。但现在我很困惑如何从我获取的列表中删除用户。我做了一个删除功能,它在手动刷新时工作正常,但不会自动刷新并返回错误。如何制作删除功能。

   const InitialState = {
  Users:  []
}

const Reducer = (state, action) =>
{
    switch(action.type)
    {
        case 'FETCH_USERS':
            return{
                Users: action.payload
            }
        case 'REMOVE_USER':
            return{

                Users: action.payload
            }
        default: 
        return state
    }
    
}
const GlobalContext = createContext(InitialState)

const GlobalState = ({children}) => {
    
    const [state, dispatch] = useReducer(Reducer, InitialState);

    useEffect(()=>
    {  
        fecthapi();
    },[])

    const fecthapi = async () =>
        {
           const res  = await axios.get('http://localhost:3002/users')
           dispatch({type: 'FETCH_USERS', payload: res.data})
        }
     
    const Remove = async  (id) =>
    {
        await  axios.delete(`http://localhost:3002/users/${id}`)
        dispatch({
        type: 'REMOVE_USER', payload: id
        
        })
       
    }
    return (
    <>
    <GlobalContext.Provider value = {{Users: state.Users, Remove: Remove}}>
        {children}
    </GlobalContext.Provider>
    </>
    )
}```
4

0 回答 0