如何通过插座上下文传递道具并从子组件内的 useOutletContext() 检索道具

问题描述 投票:0回答:1

我尝试在 Outlet React-dom-router 组件中使用上下文,并通过 Outlet 子组件中的 useOutletContext() 检索道具,如下所示

tsx 
//父组件内部 `

 
tsx
//inside outlet children components: const { purchaseData, setPurchaseData, catsData, setCatsData, isLoading, setIsLoading, affection, setAffection, affectionColor, setAffectionColor, setHeaderBackgroundColor, } = useOutletContext();

` 问题在于,如果父母和孩子的上下文模式不匹配。尽管检索到的道具具有相同的名称,但它们并不匹配。我尝试 console.log(useOutletContext() ,结果发现无法识别父 props 中的名称)。因此,在子组件中检索 props 时完全基于提供和检索的 props 的顺序。 有没有办法解决这个问题或根据名称而不是顺序检索上下文?

我尝试通过来自react-dom-router的outlet context和useOutletContext hook根据名称检索和传递props。我的期望是:数据根据名称进行匹配。发生了什么:数据不是根据名称匹配,而是根据顺序匹配。因此,如果传递的上下文和检索的上下文的顺序之间存在微小差异,应用程序就会崩溃。

reactjs react-router react-router-dom react-context
1个回答
0
投票

您应该按照提供上下文值的方式使用上下文值。

如果使用数组:

<Outlet
  context={[
    purchaseData,
    setPurchaseData,
    catsData,
    setCatsData,
    isLoading,
    setIsLoading,
    affection,
    setAffection,
    affectionColor,
    setAffectionColor,
    setHeaderBackgroundColor
  ]}
/>

那么消费者应该使用数组解构赋值来访问他们想要的值。顺序很重要,因为您正在访问数组元素

const [
  purchaseData,
  setPurchaseData,
  catsData,
  setCatsData,
  isLoading,
  setIsLoading,
  affection,
  setAffection,
  affectionColor,
  setAffectionColor,
  setHeaderBackgroundColor
] = useOutletContext();

或者如果您只想要一个子集,即仅

isLoading
setHeaderBackgroundColor
:

const [,,,, isLoading,,,,,, setHeaderBackgroundColor] = useOutletContext();

使用对象会部分消耗这些值,因为它消除了顺序要求。只需使用对象解构赋值即可。

<Outlet
  context={{
    purchaseData,
    setPurchaseData,
    catsData,
    setCatsData,
    isLoading,
    setIsLoading,
    affection,
    setAffection,
    affectionColor,
    setAffectionColor,
    setHeaderBackgroundColor
  }}
/>
const { setHeaderBackgroundColor, isLoading } = useOutletContext();
© www.soinside.com 2019 - 2024. All rights reserved.