Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs react钩子中useContext的设计问题:相似的组件,但具有不同的上下文_Reactjs_React Hooks - Fatal编程技术网

Reactjs react钩子中useContext的设计问题:相似的组件,但具有不同的上下文

Reactjs react钩子中useContext的设计问题:相似的组件,但具有不同的上下文,reactjs,react-hooks,Reactjs,React Hooks,我有一个图表组件,它由单元格组件组成。图表和单元格都使用useContext挂钩,我在外层提供了该上下文。我想创建一个类似的新图表,但使用不同的上下文。例如,原始图表根据不同的键存储和查找信息:当我填充原始上下文时,它看起来像:{'player1':[],'player2':[],'player3'…},但新的上下文看起来像:{'You':[],'Your':[],'Your opporter':[]} 我是否应该向图表组件传递一个参数/标志,告诉它使用什么上下文?然后我可以这样做:const[

我有一个
图表
组件,它由
单元格
组件组成。
图表
单元格
都使用
useContext
挂钩,我在外层提供了该上下文。我想创建一个类似的新图表,但使用不同的上下文。例如,原始图表根据不同的键存储和查找信息:当我填充原始上下文时,它看起来像:
{'player1':[],'player2':[],'player3'…}
,但新的上下文看起来像:
{'You':[],'Your':[],'Your opporter':[]}

我是否应该向
图表
组件传递一个参数/标志,告诉它使用什么上下文?然后我可以这样做:
const[selectedCombos,handleSelectedDispatch]=usePlayers?useContext(原始上下文):useContext(其他上下文)

我能做这样的事吗?我知道它很难闻,但我看到的唯一选择是将
图表
/
单元格
组件复制到一个新文件,更改其使用的上下文并重命名它。这也很糟糕。这里的正确方法是什么


我尝试过简单地将代码复制到一个新组件并使用不同的上下文,但这也很糟糕。

传递一个标志有点糟糕,因为如果您认为将来,
单元格可以使用3个不同的上下文会怎么样?还是更多

这会很糟糕。您将导入不使用的上下文

您可以做的是传递一个带有上下文的道具

e、 g

//呈现单元格的文件。
仅从“../mycontext/OnlyTheContextYouNeed”导入所需的EconTextYouneed
...
...
//Cell.jsx
...
const[selectedCombos,handleSelectedDispatch]=useContext(props.usedContext)
这样,您就不必导入
单元格中的所有上下文,只需导入渲染
单元格时所需和使用的上下文即可

// File that render the cell.
import OnlyTheContextYouNeed from '../mycontext/OnlyTheContextYouNeed'

...
    <Cell usedContext={OnlyTheContextYouNeed } />
...

//Cell.jsx    
...
const [selectedCombos, handleSelectedDispatch] = useContext(props.usedContext)