将 Reselect 与 ownProps 一起使用以获得最佳实践?

问题描述

我想从我的 redux 状态中选择流信息。这是可行的,但是当我尝试从 redux 状态中选择深度状态时,我非常困惑。我想从 state.livestream.subscribeLiveStream[postID].des 中选择 (state.livestream.subscribeLiveStream[postID].views,postID,...) 和 ownProps。这是我的代码。我的问题

  1. 选择器和组件中的代码好吗?
  2. 如果不是,请解释原因。

感谢您的帮助。 这是我所拥有的

减速器

state = {
  livestream: {
    subscribeLiveStream: {
      'a': {
        des: 'My stream a',views: 0,status: 0,},'b': {
        des: 'My stream b',}
      // 'a','b' is ID
    }
  },// other
}

选择器

const livestreamSelector = state => state.livestream;

/* select subscribeLiveStream */
export const selectSubLiveStream = createSelector(
  livestreamSelector,livestream => livestream.subscribeLiveStream
);

/* select subscribeLiveStream info */
const getPostID = (_,postID) => postID;
export const makeSelectSubLiveStreamViews = () => createSelector(
  [selectSubLiveStream,getPostID],(subLiveStream,postID) => subLiveStream[postID]?.views || 0
);

在组件中使用:

const LiveStream = ({ postID }) => {
  const selectSubLiveStreamViews = useMemo(makeSelectSubLiveStreamViews,[]);
  const views = useSelector(state =>
    selectSubLiveStreamViews(state,postID)
  );
  return (
    <div>
      <p>My stream views: {views}</p>
    </div>
  );
};

解决方法

您可以将参数 postID 作为第一个参数传递:

//pass in postId and return a selector function
export const makeSelectSubLiveStreamViews = (postId) => createSelector(
  [selectSubLiveStream],(subLiveStream) => subLiveStream[postID]?.views || 0
);

在您的组件中:

//you need to recreate the selector function when postId chages
//  or you'll get the wrong data
const selectSubLiveStreamViews = useMemo(
  ()=>makeSelectSubLiveStreamViews(postId),[postId]
);
//no need to pass postId again,code looks a little cleaner
const views = useSelector(selectSubLiveStreamViews);

Here 是我如何在 React-redux 中使用 reselect 的一些示例。