JavaScript/react/useSelector

来自康健生活
Kangkk​(留言 | 贡献)2022年6月13日 (一) 08:19的版本 (→reselect)

引言

共享状态,从 Redux 的 store 中提取数据(state)。

import { useSelector } from 'react-redux';
...
  const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView);

浅层比较

import { shallowEqual, useSelector } from 'react-redux';
...
  const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView, shallowEqual);

reselect

import { useSelector } from 'react-redux';
import { createSelector } from 'reselect';
...
  const { 'id': activeGroupId } = useSelector(createSelector(
    state => state.canvas.scrollIntoView,
    scrollIntoView => scrollIntoView.type === 'group'
  ));

示例

...
  const [activeGroupId, setActiveGroupId] = useState(0);
  const scrollIntoView = useSelector(createSelector(
    state => state.canvas.scrollIntoView,
    _ => _.type === 'group' && _
  ), shallowEqual);
  useEffect(() => {
    if (!scrollIntoView) return;
    setActiveGroupId(scrollIntoView.id);
  }, [scrollIntoView]);