我一直在学习 redux,但我的状态在选择器调用期间返回 undefined 时遇到了问题。
一些代码:
选择器:
export const selectPosts = reduxState => reduxState.posts.myPost
操作:
export const addPosts = ({ subId, postId, userId, content }) => ({
type: "posts/add",
payload: {
userId,
postId,
content,
subId
},
});
减速器:
const myPost = [],
export default function reducer(state = myPost, action) {
switch (action.type) {
case "posts/add": {
return {
...state,
myPost: [
...state.posts,
{
userId: action.payload.userId,
postId: action.payload.postId,
content: action.payload.content,
subId: action.payload.subId,
},
],
};
}
default: {
return state;
}
}
}
我用 const posts = useSelector(selectPosts);
我看了很多,虽然有很多问题与我的问题相同,但我一直没能取得任何进展。
我认为这可能与我阅读对象的方式有关,但我还没有解决
谢谢
塞缪尔-png
编辑:我收到的错误如下:
TypeError: Cannot read property 'myPost' of undefined
selectPosts
src/store/posts/selectors.js:1
> 1 | export const selectPosts = reduxState => reduxState.post.myPost
View compiled
▶ 2 stack frames were collapsed.
FrontPage
src/pages/FrontPage.js:10
7 | import { useDispatch } from "react-redux";
8 |
9 | export default function FrontPage() {
> 10 | const posts = useSelector(selectPosts);
11 | console.log(posts)
12 | return (
13 | <div>
还有商店
import userReducer from "./user/reducer";
import postReducer from "../posts/reducer";
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import ReduxThunk from "redux-thunk";
const devTools = window.__REDUX_DEVTOOLS_EXTENSION__
? window.__REDUX_DEVTOOLS_EXTENSION__()
: (x) => x;
const enhancer = compose(applyMiddleware(ReduxThunk), devTools);
const store = createStore(
combineReducers({
user: userReducer,
team: postReducer,
}),
enhancer
);
export default store;
答案 0 :(得分:0)
您正在将您的帖子映射到 combineReducers 中的团队,因此您必须通过该键在 useSelectors 中进行引用。
const posts = useSelector(state => state.team)
也不要更改传递给减速器的 initialState 的类型
您的帖子减速器中的示例,
您正在传递一个数组 myPost 作为 initialState
但是稍后从减速器返回一个对象,这可能会带来更多错误。