我是新手React
和Redux
。现在学习钩子,真的很困惑。做一个教程应用程序(老师正在使用类),它应该从 jsonplaceholder(异步)获取一些 API 数据,然后将它与 redux 一起使用。目前,我无法在屏幕上显示获取的数据。
最底部还有我的两个附加问题。
我的代码(不起作用):错误:TypeError:posts.map 不是函数
PostList.js
import React, { useEffect, useState } from "react";
import { fetchPosts } from "../actions";
import { useSelector } from "react-redux";
const PostList = () => {
const [ posts, getPosts ] = useState("");
// posts = useSelector((state) => state.posts);
// const dispatch = useDispatch();
useEffect(() => {
setPosts(fetchPosts());
}, []);
return (
<div className="ui relaxed divided list">
<ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>
</div>
);
};
export default PostList;
动作/index.js
import jsonPlaceholder from "../apis/jsonPlaceholder";
export const fetchPosts = () => async (dispatch) => {
const response = await jsonPlaceholder.get("/posts");
dispatch({ type: "FETCH_POSTS", payload: response.data });
};
apis/jsonPlaceholder.js
import jsonPlaceholder from "../apis/jsonPlaceholder";
export const fetchPosts = () => async (dispatch) => {
const response = await jsonPlaceholder.get("/posts");
dispatch({ type: "FETCH_POSTS", payload: response.data });
};
减速器/postsReducer.js
export default (state = [], action) => {
switch (action.type) {
case "FETCH_POSTS":
return action.payload;
default:
return state;
}
};
我让它工作(用以下内容在我的屏幕上显示帖子):
组件/PostList.js
import React, { useEffect, useState } from "react";
import { fetchPosts } from "../actions";
import axios from "axios";
const PostList = () => {
const [ posts, setPosts ] = useState([]);
useEffect(() => {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
console.log(response);
setPosts(response.data);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div className="ui relaxed divided list">
<ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>
</div>
);
};
export default PostList;
1)但我没有在useEffect中使用任何异步或等待。这个对吗?
2) 当我使用 useEffect 时,我应该使用中间件(如 thunk)吗?
3) 像 useSelector 和 useDispatch 这样的 redux hooks 是什么,我应该在哪里使用它们,或者我应该使用 react hooks 还是 redux hooks?
工作代码(仅更改 PostList.js 文件):
import React, { useEffect } from "react";
import { fetchPosts } from "../actions";
import { useSelector, useDispatch } from "react-redux";
const PostList = () => {
// const [ posts, setPosts ] = useState([]);
const posts = useSelector((state) => state.posts);
const dispatch = useDispatch();
useEffect(
() => {
dispatch(fetchPosts());
},
[ dispatch ]
);
return (
<div className="ui relaxed divided list">
<ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>
</div>
);
};
export default PostList;