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

Use Reselect with ownProps for best practice?

我想要 select 来自我的 redux 状态的流信息。它是有效的,但是当我从我的 redux 状态尝试 select 深层状态时,我很困惑。我想要 select(state.livestream.subscribeLiveStream[postID].desstate.livestream.subscribeLiveStream[postID].views、...)和 ownPropspostID。这是我的代码。我的问题

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

感谢您的帮助。 这是我的

减速机

state = {
  livestream: {
    subscribeLiveStream: {
      'a': {
        des: 'My stream a',
        views: 0,
        status: 0,
      },
      'b': {
        des: 'My stream b',
        views: 0,
        status: 0,
      }
      // '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 是我如何将 reselect 与 React-redux 结合使用的一些示例。