useContext中的useReducer未保存状态

时间:2020-10-18 08:05:59

标签: reactjs react-hooks react-state-management use-context use-reducer

我正在尝试从数据库中获取数据,如果获取成功,则使用useReducer,然后我希望将其作为状态返回,以便将其传递给组件。

我有console.log的req.data,它正在获取正确的数据,但是当我在化简器中返回值时,它并没有保存到状态。

状态应该是对象数组。

有人可以看到我在哪里错吗?

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

export const OrganisationsContext = createContext()

export const OrganisationsContextProvider = ( { children }) => {
    const initState = []

    const organisationsReducer = (state, action) => {
        console.log(state)
        switch(action.type) {
            case 'FETCH_SUCCESS':
                return [...state, action.payload]
            case 'FETCH_ERROR':
                throw new Error(action.payload)
            default:
                return state
        }   
    }

    useEffect(() => {
        const initFetch = async () => {
            try {
                const req = await axios.get('/api/fetch_organisations')
                organisationsDispatch({action: 'FETCH_SUCCESS', payload: req.data})
            } catch (err) {
                organisationsDispatch({action: 'FETCH_ERROR', payload: err})
            }
        }
        initFetch()
    }, [])

    const [organisations, organisationsDispatch] = useReducer(organisationsReducer, initState)

    return (
        <OrganisationsContext.Provider value={{organisations, organisationsDispatch}}>
            {children}
        </OrganisationsContext.Provider>
   

 )
}

0 个答案:

没有答案