如何使用react和redux显示来自api的数据



大家好,我很难理解使用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/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 Toolkit,它在创建操作和减少程序时节省了大量时间。另请阅读createAsyncThunk使用和RESTful API获取数据的相关内容。试试这个教程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存储中的初始数据是什么样子的,但这里是。

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;

最新更新