问题描述
我对React
和Redux
不熟悉。现在学习有关钩子的知识,真的很困惑。
做一个教程应用程序(老师正在使用课程),它应该从jsonPlacehold(异步)获取一些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;
action/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 });
};
接口/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)但我没有使用任何异步,也没有等待使用效果。这样做正确吗?
2)使用useEffect时是否应使用中间件(如thunk)?
3)像useSelector和useDispatch这样的Redux挂钩有什么用?我应该在哪里使用它们,还是应该使用Reaction挂钩或Redux挂钩?
工作代码(仅更改了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;
推荐答案
您正在使用.then
来等待调用结束,就像async
告诉代码等待
您需要使用redux-thunk
如果您想将此操作作为还原操作运行(因为使用了异步行为,.then
或者async
),useEffect
对属于您项目的还原部分的redux-thunk
的反应效果之间没有关系
您需要useDispatch
从UI调度函数
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchPosts());
}, []);
和useSelector
,用于为组件订阅还原道具(ASmapStateToProps
)
const posts = useSelector((state) => state.posts);
如果同时使用它们,const [ posts, getPosts ] = useState([]);
不需要