BAR*_*OWL 1 reactjs redux react-redux
我正在尝试根据 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)
)
Run Code Online (Sandbox Code Playgroud)
容器
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);
Run Code Online (Sandbox Code Playgroud)
减速器
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;
Run Code Online (Sandbox Code Playgroud)
您可以将用户 ID 作为参数传递到选择器函数中
export const getUserPosts = (state, userId) =>
createSelector(
postSelector,
state => state.posts.filter(user => user.userId === userId)
)
Run Code Online (Sandbox Code Playgroud)
并利用react-redux中的useSelector钩子。因此,在您想要显示它们的组件中,假设您有一个用户 id 作为 prop
import { useSelector } from 'react-redux'
import { getUserPosts } from "./../selectors/selectors"
const Profile = props => {
const { userId } = props
const posts = useSelector(state => getUserPosts(state, userId)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4904 次 |
| 最近记录: |