JavaScript/react/useSelector:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
第7行: 第7行:
</syntaxhighlight>
</syntaxhighlight>


{{Warning|<div>useSelector 函数内部使用 <code>===</code> 进行数值对比,需要避免不必要的新对象返回(eq: 使用 map 等)以免触发 action 导致发生重新渲染。</div>}}
{{Warning|useSelector 函数内部使用 <code><nowiki>===</nowiki></code> 进行数值对比,需要避免不必要的新对象返回(eq: 使用 map 等)以免触发 action 导致发生重新渲染。}}


== 浅层比较 ==
== 浅层比较 ==

2022年6月20日 (一) 03:56的最新版本

引言

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

import { useSelector } from 'react-redux';
...
  const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView);
Warning: useSelector 函数内部使用 === 进行数值对比,需要避免不必要的新对象返回(eq: 使用 map 等)以免触发 action 导致发生重新渲染。

浅层比较

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]);