React -在同级组件之间共享状态和方法



这是一个设计或反应模式相关的问题,但我正试图找出在不同的孩子之间共享安全和方法的最佳方法。

我有一个小的应用程序,从一步到一步的导航和实际的表单数据在不同的兄弟组件中呈现和处理。这是一个代码盒,大致说明了应用程序是如何工作的。

我想弄清楚的是在兄弟组件之间共享状态的最佳方式。例如,在上面链接的应用程序中,我需要在单击next时验证来自<AppStepOne />的输入,然后移动到<AppStepTwo />。理想情况下,我不想让所有的状态都生活在顶级ExampleApp中,因为有相当多的步骤,而且很快就会变得丑陋。

另一个虽然我有,我想得到一些输入什么使用react上下文api。我以前没有使用过它,所以我想得到一些想法,如果它可能是一个干净的解决方案。

以上应用程序代码:

const ExampleApp = () => {
const [currentStep, setCurrentStep] = useState(1);
const getCurrentAppStep = () => {
switch (currentStep) {
case 1:
return {
app: <AppStepOne />,
navigation: (
<AppNavigation onNext={() => setCurrentStep(currentStep + 1)} />
)
};
case 2:
return {
app: <AppStepTwo />,
navigation: (
<AppNavigation onNext={() => setCurrentStep(currentStep + 1)} />
)
};
default:
return {
app: <AppStepOne />,
navigation: (
<AppNavigation onNext={() => setCurrentStep(currentStep + 1)} />
)
};
}
};
const myAppStep = getCurrentAppStep();
return (
<div>
<ParentComp>
<ChildOne>{myAppStep.app}</ChildOne>
<ChildTwo>{myAppStep.navigation}</ChildTwo>
</ParentComp>
</div>
);
};
const ParentComp = ({ children }) => {
return <div>{children}</div>;
};
const ChildOne = ({ children }) => {
return <div>{children}</div>;
};
const ChildTwo = ({ children }) => {
return <div>{children}</div>;
};
const AppStepOne = () => {
const [name, setName] = useState("");
return (
<div>
Name: <input onChange={(e) => setName(e.target.value)} />
</div>
);
};
const AppStepTwo = () => {
const [zipcode, setZipCode] = useState("");
return (
<div>
Zipcode: <input onChange={(e) => setZipCode(e.target.value)} />
</div>
);
};
const AppNavigation = ({ onNext }) => {
return <button onClick={onNext}>Next</button>;
};

我相信你在这里的选择是

  1. 具有全局存储(考虑redux或其他状态管理解决方案)
  2. 在组件周围有一个上下文,并从这个上下文共享状态
  3. 如果你熟悉钩子,考虑这个叫做use-between的开源项目,它用一个非常简单的API完成了你想要的。这里的

最新更新