JavaScript/react/useSelector:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
无编辑摘要
Kangkk​(留言 | 贡献)
 
(未显示同一用户的3个中间版本)
第6行: 第6行:
   const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView);
   const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView);
</syntaxhighlight>
</syntaxhighlight>
{{Warning|useSelector 函数内部使用 <code><nowiki>===</nowiki></code> 进行数值对比,需要避免不必要的新对象返回(eq: 使用 map 等)以免触发 action 导致发生重新渲染。}}


== 浅层比较 ==
== 浅层比较 ==
第24行: 第26行:
     scrollIntoView => scrollIntoView.type === 'group'
     scrollIntoView => scrollIntoView.type === 'group'
   ));</syntaxhighlight>
   ));</syntaxhighlight>
== 示例 ==
<syntaxhighlight lang="javascript">
...
  const [activeGroupId, setActiveGroupId] = useState(0);
  const scrollIntoView = useSelector(createSelector(
    state => state.canvas.scrollIntoView,
    _ => _.type === 'group' && _
  ), shallowEqual);
  useEffect(() => {
    if (!scrollIntoView) return;
    setActiveGroupId(scrollIntoView.id);
  }, [scrollIntoView]);</syntaxhighlight>