【问题标题】:How do I display data from api using react and redux如何使用 react 和 redux 显示来自 api 的数据
【发布时间】:2021-04-26 23:23:46
【问题描述】:

您好,我很难理解如何使用 React 和 Redux 从 API 访问数据,有人能给我一些指导吗,到目前为止,我只想显示小App.js 中的一段数据,看看它现在是如何工作的。任何帮助将不胜感激,谢谢。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux'
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk'
import {reducers} from './reducers'
import App from './App';

const store = createStore(reducers, compose(applyMiddleware(thunk)));

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

App.js

import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { getData } from "./actions/actions";


const App = () => {
  const [title, setTitle] = useState(0);
  const [description, setDescription] = useState(0);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getData());
  }, [title, dispatch]);



  return (
    <div className="App">
      <h1>Hello</h1>
      {/* {posts.map((post)=>(
        <h1>{post.title}</h1>
      ))} */}
      {/* Trying to display title and description */}
      <h1>{title.title}</h1>  
      <h1>{description.description}</h1>  


    </div>
  );
};

export default App;

动作/actions.js

import * as api from "../api/index"


export const getData = () => async(dispatch) => {
    try {
        const {data} = await api.fetchData();
        
        dispatch({ type: 'FETCH', payload: data });
    } catch(error) {
        console.log(error.message);
    }
};

reducers/data.js

export default (data = [], action) => {
  switch (action.type) {
    case "FETCH":
      return action.payload;
    default:
      return data;
        
  }
};

reducers/index.js

import { combineReducers } from 'redux';


import data from "./data";

export const reducers = combineReducers({ data })

API

import axios from "axios";

const url = "http://localhost:5000/routes";

export const fetchData = () => axios.get(url);

目前数据库中只有一条数据,即标题和描述。

【问题讨论】:

  • 您需要使用redux 工具包来显示您的数据

标签: javascript reactjs redux react-redux axios


【解决方案1】:

你应该试试 Redux Toolkit,它可以节省大量创建动作和 reducer 的时间。另请阅读有关使用 RESTful API 获取数据的 createAsyncThunk。 试试这个教程https://www.softkraft.co/how-to-setup-slices-with-redux-toolkit/ 并查看文档https://redux-toolkit.js.org/api/createAsyncThunk

【讨论】:

    【解决方案2】:

    您没有从 App.js 中的 redux 商店引用任何内容。 要从存储中调用数据,您需要使用 useSelecter 钩子。

    我假设您的代码不完整? 如果不是, useEffect 钩子在这里是多余的。 useDispatch 和 useState 钩子也是如此。

    下面是使用 redux 工具包编辑的代码。 是目前推荐使用 redux 的库。 我忘记了我学到的关于 action 和 reducer 的知识。

    我不确定你在 redux 存储中的初始数据是什么样子的,但这里是。

    App.js

    import React from "react";
    import { useSelector } from "react-redux";
    import { getData } from "./actions/actions";
    
    
    const App = () => {
      const {data} = useSelecter((state) => state)
      const dispatch = useDispatch();
    
      useEffect(() => {
       fetch("http://localhost:5000/routes")
        .then(res => {
          return res.json();
        })
        .then(data => {
         // dispatch to store
        })
       }, []);
    
    
    
      return (
        <div className="App">
          <h1>Hello</h1>
          {/* {posts.map((post)=>(
            <h1>{post.title}</h1>
          ))} */}
          {/* Trying to display title and description */}
          <h1>{data.title}</h1>  
          <h1>{data.description}</h1>  
        </div>
      );
    };
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2018-01-04
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多