How can I access complete state in redux?
const { createStore } = require("redux");
const initialState = {
posts: [
{ id: 1, title: "Post one" },
{ id: 2, title: "Post two" },
],
};
我的帖子减少器
const PostsReducer = (state = initialState, action) => {
switch (action.type) {
case "add_post":
return {
...state,
posts: [...state.posts, action.payload],
};
case "delete_post":
return {
...state,
posts: state.posts.filter((post) => post.id !== action.payload),
};
case "get_all_posts":
return state.posts;
default:
return state;
}
};
const store = createStore(PostsReducer);
我的动作创作者:
const GetAllPosts = () => {
return {
type: "get_all_posts",
};
};
const AddPost = (payload) => {
return { type: "add_post", payload };
};
const removePost = (payload) => {
return { type: "delete_post", payload };
};
访问store 数据:
store.subscribe(() => {
const data = store.getState();
console.log(data.posts);
});
store.dispatch(GetAllPosts());
当我在控制台登录data.posts
时,它返回undefined
.
我正在使用订阅者方法访问:
store.subscribe(() => {
const data = store.getState();
console.log(data.posts);
});
store.dispatch(GetAllPosts());
注:
我正在使用Redux(4.2.1)
通过使用GetAllPosts()
,我可以访问数据,但我无法在控制台中获取data.posts
.