我正在尝试根据userId检索所有帖子。我不确定如何使逻辑正常工作,以及在整个应用程序中可恢复使用的逻辑。
我希望能够调用选择器getUserPosts
,并能够在用户个人资料页面上对其进行迭代,我该怎么做?
这就是我所拥有的
选择器
export const getPosts = () => // this gets all posts
createSelector(
postSelector,
(state) => state.posts,
);
export const getUserPosts = () => // how i do i get all posts based on user id i pass state here
createSelector(
postSelector,
(state) => state.posts.filter((user) => user.userId === state.id)
)
容器
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import Profile from "./../components/Profile/Profile"
import { getUserPosts } from "./../selectors/selectors";
const mapStateToProps = createStructuredSelector({
userPosts: getUserPosts()
});
export default connect(
mapStateToProps,
null,
)(Profile);
减速器
import produce from "immer";
import * as types from "../actionTypes/postActionTypes";
import { validation } from '../utils';
export interface postState {
posts: any[];
postPage: any;
error: any;
titleError: any;
bodyError: any;
title: string
postContent: string
}
const initialState: postState = {
posts: [],
postPage: {},
titleError: null,
bodyError: null,
title: "",
postContent: "",
error: null
};
const postReducer = (state = initialState, action: any): postState =>
produce(state, (draft) => {
switch (action.type) {
case types.GET_POSTS_SUCCESS:
draft.posts = action.payload;
return;
}
});
export default postReducer;
答案 0 :(得分:1)
您可以将用户ID作为参数传递到选择器函数中
export const getUserPosts = (state, userId) =>
createSelector(
postSelector,
state => state.posts.filter(user => user.userId === userId)
)
并利用react-redux中的useSelector钩子。因此,假设您有一个用户ID作为道具,则要在组件中显示它们
import { useSelector } from 'react-redux'
import { getUserPosts } from "./../selectors/selectors"
const Profile = props => {
const { userId } = props
const posts = useSelector(state => getUserPosts(state, userId)
}