Axios调用useReducer返回承诺,而不返回数据

时间:2020-10-17 01:12:53

标签: reactjs react-hooks use-reducer

我在上下文提供程序中使用useReducer。我的想法是,我将成为状态和调度功能正常运行的中心。

我正在对数据仓库进行axios调用以获取项目。但是,当我返回调度函数时,它正在返回一个promise。如何从axios调用返回数据,以便将调用状态的数据存储在状态中?

const initState = []

const projectsReducer = async (state, action) => {
    switch(action.type) {
        case 'FETCH_PROJECTS':
            const req = await axios.get('/api/fetch_projects')
            const { data } = req
            return {...state, data}
            
        default: 
            return state

    }
}

useEffect(() => {
    const initFetch = () => {
        projectsDispatch({type: 'FETCH_PROJECTS'})
    }
    initFetch()
}, [])


const [projects, projectsDispatch] = useReducer(projectsReducer, initState)

1 个答案:

答案 0 :(得分:1)

在效果中进行提取,然后将数据传递到reducer。

reducer是一个纯函数,不应有任何副作用。另外,将从减速器返回的所有数据设置为下一个状态。因此,异步函数始终会返回一个Promise-这意味着您将projects的状态设置为数据的Promise。

如果您按照以下方式重构代码,它应该可以工作。

const initState = {data: []};

const projectsReducer = (state, action) => {
    switch(action.type) {
        case 'FETCH_PROJECTS':
            const { data } = action.payload;
            return {...state, data}
            
        default: 
            return state

    }
}
const [projects, projectsDispatch] = useReducer(projectsReducer, initState)

useEffect(() => {
    const initFetch = async () => {
        const req = await axios.get('/api/fetch_projects')
        projectsDispatch({type: 'FETCH_PROJECTS', payload: {data: req.data}})
    }
    initFetch()
}, [])
// data is in projects.data;

尽管它更简单,但您实际上并不需要减速器:

const [projects, setProjects] = useState([]);

useEffect(() => {
    const initFetch = async () => {
        const req = await axios.get('/api/fetch_projects')
        setProjects(req.data);
    }
    initFetch()
}, [])
// data is in projects