需要澄清 react + react-redux hooks + middleware thunk + fetching API

IT技术 reactjs redux react-redux react-hooks redux-thunk
2022-07-13 02:00:14

我是新手ReactRedux现在学习钩子,真的很困惑。做一个教程应用程序(老师正在使用类),它应该从 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;
1个回答
  1. 您正在使用.then等待呼叫结束,就像async告诉代码等待一样

  2. redux-thunk如果您想将此操作作为 redux 操作运行,则需要使用(因为使用了异步行为),.then两者async之间没有关系,即属于您项目的 redux 部分的useEffectreact效果redux-thunk

  3. 你需要useDispatch从 UI 调度函数


 const dispatch = useDispatch()

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

useSelector为组件订阅 redux props(as mapStateToProps


  const posts = useSelector((state) => state.posts);

如果您同时使用它们,则const [ posts, getPosts ] = useState([]);不需要