JavaScript/react/useSelector:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的4个中间版本)
第7行: 第7行:
</syntaxhighlight>
</syntaxhighlight>


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


== 浅层比较 ==
== 浅层比较 ==
第16行: 第16行:
   const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView, shallowEqual);
   const { 'id': activeGroupId } = useSelector(state => state.canvas.scrollIntoView, shallowEqual);
</syntaxhighlight>
</syntaxhighlight>
== reselect ==
<syntaxhighlight lang="javascript">
import { useSelector } from 'react-redux';
import { createSelector } from 'reselect';
...
  const { 'id': activeGroupId } = useSelector(createSelector(
    state => state.canvas.scrollIntoView,
    scrollIntoView => scrollIntoView.type === 'group'
  ));</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>