【发布时间】: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