React组件未更新新的Redux状态

dy2hfwbg  于 9个月前  发布在  React
关注(0)|答案(1)|浏览(86)

我的问题是,一个组件似乎没有收到正确的redux状态(及时?),因此在此redux状态下不显示侧边栏组件。调用的页面看起来像:

const MyLandingPage: NextPage = () => {
  const { setLayout } = useSetLayout(); // the Redux dispatch method, see below
  ...
  useEffect(
    () => {
      setLayout({
        sidebar: {
          content: <FeedSidebar filters={filters} setFilters={setNewFilters} />
      });
    },
    [...]
  );
  return <MyComponent ... />
}

此页面将嵌入到我的Layout.tsx的侧列中:

export const Layout: React.FC = () => {
  const sidebar = useSidebarContentSelector(); // the Redux selection method, see below
  console.log('sidebar in Layout:', sidebar);
  return <SomeOtherComponents>{sidebar?.content}<SomeOtherComponents>;
}

侧边栏状态的Redux相关钩子看起来像这样:

export const useSidebarContentSelector = () => useSelector((state: RootState) => state.sidebarContent);

export const useSetLayout = () => {
  const { setSidebar } = sidebarContentSlice.actions;
  const dispatch = useAppDispatch();
  return {
    setLayout: (commands: { sidebar?: SidebarState) => {
      console.log('setting sidebar:', commands.sidebar);
      dispatch(setSidebar(commands.sidebar));
    }
  }  
}

日志内容如下:

sidebar in Layout: null
setting sidebar: Object { content: {…} }
sidebar in Layout: null

useSidebarContentSelectoruseSidebarContentDispatch在其他情况下工作,我相当肯定他们是好的。但是由于某种原因,Layout.tsx中的侧边栏没有接收到更新,我认为只是继续显示SSR的状态。
我很感激任何想法,为什么更新的侧边栏没有收到dispite正在派遣和Layout组件重新渲染!

qoefvg9y

qoefvg9y1#

找到了。我没有使用Redux商店单例,所以每次重新渲染都会创建一个新商店。一种解决方案可能是使用const store => useMemo(() => configureStore(...), [])创建存储,但对于我的设计来说,使用它更直接

const isServerSide = typeof window === 'undefined';

const clientSideReduxStore = configureStore(...);

export const ReduxProvider: React.FC<
  Omit<ProviderProps, 'store'> & { preloadedState?: Partial<RootState> }
> = (props) => {
  return isServerSide ? Provider({store: configureStore(...)) : clientSideReduxStore
}

请注意,在SSR上,任何调用都必须创建一个新的存储,所以如果我在服务器端,我不能返回clientSideReduxStore

相关问题