【问题标题】:Retrieve data from API using Redux使用 Redux 从 API 检索数据
【发布时间】:2021-11-15 22:48:14
【问题描述】:

昨晚,我使用 Redux 编写了一个非常基本的计数器应用程序,现在想通过使用 fetch 从第三方 API 获取数据来再次执行相同的操作。但是,我有点迷茫(因为我才刚刚开始使用 redux)并且需要帮助来了解如何从这里开始并使用 Redux 成功地进行 API 调用。我的代码如下:

action.js

import { useDispatch } from "react-redux";

export const getData = () => async() => {
    await fetch('https://api.instantwebtools.net/v1/airlines', {
        method : 'GET'
    }).then(
        res => res.json()
    ).then(
        data => useDispatch({
            type : "GET_DATA",
            payload : data
        })
    );
};

reducer.js

const FetchData = (state = {}, action) => {
    switch (action.type) {
        case "GET_DATA":
            return {...state};
        default:
            return state;
    }
};

export default FetchData;

combineReducer.js(将reducer发送到index.js文件)

import { combineReducers } from "redux";
import FetchData from "./fetchData";

const reducer = combineReducers({
    get : FetchData
});

export default reducer;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from './reducers';

const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
reportWebVitals();

screen.jsx

import React from "react";
import { useSelector } from "react-redux";

const Screen = () => {
    const selector = useSelector(state => state.get);

    return (
        <div>
            {selector.map((key, value) => <ul>
                <li>{selector[value].name}</li>
            </ul>
            )}
        </div>
    );
};

export default Screen;

上述组件中的想法是仅在无序列表中显示从 json 响应中检索到的 name 属性。但是,鉴于我在 Redux 方面的业余经验,我想知道如何实现它。我得到的错误提示如下:

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

map 似乎由于某种原因无法正常工作,但这可能是因为 API 调用根本不成功。我无法弄清楚第一个错误是什么意思。

API 的链接是:https://api.instantwebtools.net/v1/airlines 此外,我还分享了响应的实际样子的一个小 sn-p

[
  {
  "id": 1,
  "name": "Quatar Airways",
  "country": "Quatar",
  "logo": "https://upload.wikimedia.org/wikipedia/en/thumb/9/9b/Qatar_Airways_Logo.svg/300px-Qatar_Airways_Logo.svg.png",
  "slogan": "Going Places Together",
  "head_quaters": "Qatar Airways Towers, Doha, Qatar",
  "website": "www.qatarairways.com",
  "established": "1994"
  },
  {
  "id": 2,
  "name": "Singapore Airlines",
  "country": "Singapore",
  "logo": "https://upload.wikimedia.org/wikipedia/en/thumb/6/6b/Singapore_Airlines_Logo_2.svg/250px-Singapore_Airlines_Logo_2.svg.png",
  "slogan": "A Great Way to Fly",
  "head_quaters": "Airline House, 25 Airline Road, Singapore 819829",
  "website": "www.singaporeair.com",
  "established": "1947"
  },
]

【问题讨论】:

  • 您对 dispatch 的使用不正确。 useDispatch 是一个需要在反应组件中的钩子。在这里你需要引用store.dispatch
  • const dispatch = useDispatch(); // ... dispatch({ type : "GET_DATA", payload: data })
  • 你在这里写的是一个相当过时的 Redux 风格——现代 Redux 不使用 switch..case reducers、ACTION_TYPES 或 createStore。我建议您遵循官方的 Redux 教程,该教程还将在第 5 章中向您展示如何手动执行 api 请求,并在第 8 章中向您展示如何自动化大部分代码。 redux.js.org/tutorials/essentials/part-1-overview-concepts

标签: reactjs redux react-redux


【解决方案1】:

这里是一个简单的 react/redux 设置示例的链接。有很多方法可以做到这一点,这只是其中一种方法。我使用了相同的 API,但使用了不同的端点,因为前一个返回了大约 10000 个项目,codeandbox 有点抱怨,但原理是一样的。

希望这会有所帮助! :) https://codesandbox.io/s/stackoverflow-dude-f7bbo?file=/src/App.js

【讨论】:

  • 非常感谢您提供的链接,帮助我解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多