JavaScript/react/useSelector:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
创建页面,内容为“== 引言 == 共享状态,从 Redux 的 store 中提取数据(state)。 <syntaxhighlight lang="javascript"> import { useSelector } from 'react-redux'; ... const…”
 
Kangkk​(留言 | 贡献)
 
(未显示同一用户的5个中间版本)
第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 导致发生重新渲染。}}


== 浅层比较 ==
== 浅层比较 ==
第14行: 第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>