【发布时间】:2021-05-06 01:50:42
【问题描述】:
我一直在学习 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);调用选择器
我看了很多,虽然有很多问题与我的问题相同,但我无法取得任何进展。
我认为这可能与我阅读对象的方式有关,但我还没有解决它
谢谢
Samuele-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;
【问题讨论】:
-
您将 initialState 作为数组 state=myPosts 开始,然后在您的帖子/添加操作中返回一个对象 - return {...state, myPost: []}
-
你能分享数据在你的 redux 状态下是如何存储的吗?
-
嘿!你的意思是 store.js 吗?我把它添加到主帖
-
您正在将 postReducer 重命名为 team。因此,在选择时,您必须通过该名称引用它。 const post = useSelector(state => state.team)
-
嘿 abishek 非常感谢你,为我解决了这个问题。我不敢相信我被困了几个小时,而答案就在我面前。非常感谢!!!!!!
标签: javascript reactjs redux react-redux