【问题标题】:How to call redux-thunk's dispatch?如何调用 redux-thunk 的 dispatch?
【发布时间】:2021-08-11 08:18:37
【问题描述】:

我有以下操作

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

评论.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: dispatch is not a function

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

【问题讨论】:

    标签: reactjs react-redux redux-thunk


    【解决方案1】:

    如果您想使用钩子,您需要通过useDispatch 获取对dispatch 函数的引用。此外,您可以直接导入 thunk,而不是通过 props 传递它

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

    【讨论】:

    • 感谢您的回复。我修改了代码并将问题编辑为您给出的答案,但是这次我收到了一个新错误,TypeError: Object(...) is not a function。这种情况该怎么办?
    • @Jay0813 您正在从react 导入useDispatch 而不是react-redux
    • 我一定是疯了一段时间。非常感谢您的回答。祝你有美好的一天!
    • 不客气,谢谢你和你一样
    【解决方案2】:

    首先使用来自react-reduxuseDispatch React 钩子,然后调度操作。 useSelector 钩子用于选择你的 redux 状态块。

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

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 2020-04-16
      • 2017-10-31
      • 1970-01-01
      • 2019-01-27
      • 2017-04-30
      • 2021-04-26
      • 2017-06-09
      • 2018-05-26
      相关资源
      最近更新 更多