【问题标题】:Calling API in redux在 redux 中调用 API
【发布时间】:2021-11-28 17:46:57
【问题描述】:
//Store
import { configureStore } from "@reduxjs/toolkit";
import { currencyListSlice } from "./Reducers/CurrencyListReducer";

export const store = configureStore({
    reducer: {
        currencyList: currencyListSlice.reducer,
    }
}
)

export default store

//CurrencyListReducer

import { createSlice } from "@reduxjs/toolkit"

export const loadCurrencyList = () => {
    return async (dispatch, getState) => {
        const data = await fetch(API-Key)
        const payload = await data.json()
        
        dispatch({
            type: 'currencyList/setCurrencyList',
            payload: payload
        })
    }
}

const options = {
    name: 'currencyList',
    initialState: [],
    reducers: {
        setCurrencyList(state, action) {
            return action.payload
        }
    }
}

export const currencyListSlice = createSlice(options)

//CurrencyList Component

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { currencyListSlice } from '../../Reducers/CurrencyListReducer'

const selectCurrencyList = state => state.CurrencyList

export const CurrencyList = () => {

    const dispatch = useDispatch()

    const currencyList = useSelector(selectCurrencyList)

    const { loadCurrencyList } = currencyListSlice.actions

    useEffect(() => {
        dispatch(loadCurrencyList())
    }, [dispatch, loadCurrencyList])

    console.log(currencyList)

    return (
        <div>
            /*Some elements here*/
        </div>
    )
}

我是第一次使用 redux,在调用 API 和在存储中存储数据时遇到了一些实际问题。问题是我没有从 API 中得到任何东西,但 console.log(currencyList) 只是给了我 undefined。我尝试直接在 reducer 中调用 API,但也没有成功。我是 redux 的新手,在 redux 中调用 API 对我来说是一项艰巨的任务。原谅任何愚蠢的错误(如果存在)。

【问题讨论】:

    标签: reactjs redux react-redux middleware


    【解决方案1】:

    尝试阅读:createAsyncThunk

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 2016-07-21
      • 2019-02-21
      • 2018-09-20
      • 2021-11-21
      • 2019-10-01
      • 2021-08-20
      • 2018-03-31
      相关资源
      最近更新 更多