gpt4 book ai didi

reactjs - 通过 id 重新选择 createSelector

转载 作者:行者123 更新时间:2023-12-05 03:41:30 27 4
gpt4 key购买 nike

我在我的 React 项目中使用 reselect 库。

我创建了工作正常的 Posts 选择器。这是代码

// selectors.ts

const getPosts = (state: RootState) => state.posts.posts;

export const getPostsSelector = createSelector(getPosts, (posts) => posts);

我在我的页面上这样调用它

// SomePage.tsx    
const posts = useSelector(getPostsSelector);

现在我需要通过 id 获取帖子。我想这样做:

// selectors.ts

const getPostDetail = (state: RootState) =>
state.posts.posts.entities[ID];

export const getPostsById = createSelector(
getPostDetail,
(detail) => detail
);

并在页面上调用:

const PostDetail = useSelector(getPostsById);

我有两个问题:

  • 获取单个帖子是否正确?
  • 如果是,如何传递帖子 ID 如果不是,如何正确处理?

最佳答案

这里的问题是 react-redux 作为 HOC 有 connect(...) 函数,它允许选择器是 (state, props ) => ...,而 useSelector 仅传递 (state) => ...

要允许仍然传递 props,您可以实现 useSelectorWithProps:

function useSelectorWithProps (selector, props, deps, equalityFn) {
const selectorFn = useCallback(state => selector(state, props), deps)
return useReduxSelector(
selectorFn,
equalityFn
)
}

然后您可以执行以下操作:

// selectors.js

const selectPosts = (state) => state.posts.posts;

const selectPostById = createSelector(
selectPosts,
(_, props) => props.id,
(posts, id) => posts[id]
)

// Or make a utility function for selecting the prop
const selectProp = (key, orDefault) => (_, props) => (props[key] || orDefault)

const selectPostById = createSelector(
selectPosts,
selectProp('id'),
(posts, id) => posts[id]
)

// but don't do this, as it will de-optimize the memoization of reselect.
// `{id: 1} !== {id: 1}` and thus causes it to recalculate the selector
// (Keyword: referential equality)
const selectPostById = createSelector(
selectPosts,
(_, props) => props,
(posts, { id }) => posts[id]
)
// component.js
function Component(props) {
const value = useSelectorWithProps(
selectPostById,
{ id: props.id }, // pass an object
[ props.id ] // pass dependencies of the props-object
)
}

这就是我在我工作的项目中实现它的方式。

这允许您的完整“选择器逻辑”仍然存在于您的选择器中,使其更容易测试并且不必在 Hook 中编写更少的胶水代码。

如果您愿意,它还允许您对 connect(...)useSelectorWithProps(..) 使用相同的选择器。

关于reactjs - 通过 id 重新选择 createSelector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67699094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com