如何调用 redux-thunk 的调度?

How to call redux-thunk's dispatch?

提问人:Jay0813 提问时间:5/22/2021 最后编辑:Jay0813 更新时间:5/22/2021 访问量:370

问:

我有以下操作

export const fetchCommentRequest = () => {
  return {
    type: FETCH_COMMENTS_REQUEST,
  };
};

export const fetchComments = () => {
  return (dispatch) => {
    dispatch(fetchCommentRequest());
    fetch("https://jsonplaceholder.typicode.com/comments")
      .then((res) => res.json())
      .then((comments) => dispatch(fetchCommentSuccess(comments)))
      .catch((err) => dispatch(fetchCommentFailure(err)));
  };
};

index.js

import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./redux/rootReducer";
import logger from "redux-logger";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
const middleware = [thunk, logger];
const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(...middleware))
);
console.log(store.getState());
ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

CommentsContainer.js

function CommentsContainer() {
      const { comments, loading } = useSelector((state) => ({
        comments: state.comments.items,
        loading: state.comments.loading,
      }));
    
      return (
        <Comments
          loading={loading}
          comments={comments}
        />
      );
    }

Comments.js

import React, { useEffect, useDispatch } from "react";
import { fetchComments } from "../redux/index";

const Comments = ({ comments, loading }) => {
  const dispatch = useDispatch();

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

  const commentsItems = loading ? (
    <div>is loading...</div>
  ) : (
    comments.map((comment) => (
      <div key={comment.id}>
        <h3>{comment.name}</h3>
        <p>{comment.email}</p>
        <p>{comment.body}</p>
      </div>
    ))
  );

  return <div className="comments">{commentsItems}</div>;
};

export default Comments;

我想使用 redux-thunk 的调度来调用一个操作。但问题是当我调用此操作时,我会进入控制台。

TypeError:调度不是函数

我使用了useSelector,而不是connect()。 我通过connect()解决了这个问题,但是这次我想使用useSelector,所以我尝试并得到了一个错误。我需要做些什么来解决这个问题?

enter image description here

reactjs reactux redux redux-thunk

评论


答:

1赞 Asaf Aviv 5/22/2021 #1

如果要使用 hooks,则需要通过 useDispatch 获取对函数的引用。此外,您可以直接导入 thunk,而不是通过dispatchprops

import { useDispatch } from 'react-redux'
import fetchComments from 'path..'

const Comments = ({ comments, loading }) => {
  const dispatch = useDispatch()
  
  useEffect(() => {
    dispatch(fetchComments());
  }, []);

  const commentsItems = loading ? (
    <div>is loading...</div>
  ) : (
    comments.map((comment) => (
      <div key={comment.id}>
        <h3>{comment.name}</h3>
        <p>{comment.email}</p>
        <p>{comment.body}</p>
      </div>
    ))
  );

  return <div className="comments">{commentsItems}</div>;
};

评论

0赞 Jay0813 5/22/2021
感谢您的回复。我修改了代码并编辑了问题作为您给出的答案,但这次我收到一个新错误,TypeError:Object(...) 不是函数。在这种情况下该怎么办?
0赞 Asaf Aviv 5/22/2021
@Jay0813 您正在从useDispatch reactreact-redux
0赞 Jay0813 5/22/2021
我一定疯了一段时间。非常感谢您的回答。有好的一天!
0赞 Asaf Aviv 5/22/2021
不客气,谢谢你,也一样
0赞 Drew Reese 5/22/2021 #2

首先使用 React 钩子 from ,然后调度操作。钩子用于选择 redux 状态的块。useDispatchreact-reduxuseSelector

import { useDispatch } from 'react-redux';

const Comments = ({ comments, loading }) => {
  const dispatch = useDispatch();

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

  const commentsItems = loading ? (
    <div>is loading...</div>
  ) : (
    comments.map((comment) => (
      <div key={comment.id}>
        <h3>{comment.name}</h3>
        <p>{comment.email}</p>
        <p>{comment.body}</p>
      </div>
    ))
  );

  return <div className="comments">{commentsItems}</div>;
};