簡體   English   中英

如何使用 react 和 redux 顯示來自 api 的數據

[英]How do I display data from api using react and redux

您好,我很難理解使用 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')
);

應用程序.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);
    }
};

減速器/data.js

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

減速器/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 Toolkit,它可以節省大量創建動作和減速器的時間。 另請閱讀有關使用 RESTful API 獲取數據的 createAsyncThunk。 試試這個教程https://www.softkraft.co/how-to-setup-slices-with-redux-toolkit/並查看文檔https://redux-toolkit.js.org/api/createAsyncThunk

您沒有從 App.js 中的 redux 存儲中引用任何內容。 要從存儲中調用數據,您需要使用 useSelecter 掛鈎。

我假設您的代碼不完整? 如果不是, useEffect 鈎子在這里是多余的。 useDispatch 和 useState 鈎子也是如此。

下面是使用 redux 工具包編輯的代碼。 目前推薦使用 redux 的庫。 我已經忘記了我對動作和減速器的了解。

我不確定您在 redux 商店中的初始數據如何,但這里有。

應用程序.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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM