【问题标题】:Need clarification for react + react-redux hooks + middleware thunk+ fetching API需要澄清 react + react-redux hooks + middleware thunk + fetching API
【发布时间】:2020-09-21 19:36:35
【问题描述】:

我是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;

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 });
};

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 });
};

reducers/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) axios 返回一个你正在链接的 Promise,不需要 async/await (2) 也许只有当你在做外部异步工作时,比如数据获取 (???) 和您想将该结果存储在您的 redux 商店中(3)很难按照您的要求在这里。
  • (1) 使用类时,需要async/await,为什么这里会有所不同? (3) 对不起,想知道,如果我使用useSelector,是否需要useState?
  • (1) 有需要吗? :D 看起来像一个 (false) 假设,Promises 和 Promise 链的工作原理相同 (3) 不是真的,但这是组件状态和应用程序状态之间的区别。这完全取决于您的应用程序结构和组件需求。如果其他组件需要访问这些帖子,或者如果您想持久化它们,那么应用程序状态是显而易见的选择,但如果没有其他人关心它们并且它们是瞬态的,那么只需使用组件状态并减少复杂性和移动部分。跨度>
  • 顺便说一句,async/await 只是语法糖,使用 (drumroll) ...Promises 使异步代码“看起来”和“感觉”更像常规同步代码。它们并不完全等同,但它们涵盖了大部分相同的功能,但边缘情况略有不同。

标签: reactjs redux react-redux react-hooks redux-thunk


【解决方案1】:
  1. 您正在使用.then 等待呼叫结束,就像async 告诉代码等待一样

  2. 如果你想将这个动作作为redux动作运行,你需要使用redux-thunk(因为使用了异步行为,.then或者async),useEffect之间没有关系,即对属于你项目的 redux 部分的redux-thunk 做出反应

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


 const dispatch = useDispatch()

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

useSelector 为组件订阅redux prop(如mapStateToProps


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

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

【讨论】:

    猜你喜欢
    • 2021-06-03
    • 1970-01-01
    • 2019-02-02
    • 2022-01-05
    • 2020-08-15
    • 2019-11-08
    • 2019-10-22
    • 2012-06-02
    • 1970-01-01
    相关资源
    最近更新 更多