JavaScript/react/useSelector
来自康健生活
< JavaScript | react
引言
共享状态,从 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]);
No categories