我有一个以下形式的React应用:
<App>
<ParentComponent>
<FormComponent>
<AnotherComponent>
</ParentComponent>
</App>
我希望能够通过单击<FormComponent>
中的元素来更新<AnotherComponent>
的某些状态值。
我不想将它们放置在彼此内部,而是将它们并排放置。我不想提升<FormComponent>
状态,因为它已经很好地封装了。
实现此目标的最佳方法是什么?我可以只做一下就做吗,还是需要RxJS /其他?
答案 0 :(得分:3)
React Flows Down中的数据。
如果您不想lift the state up,剩下的就是Context API或任何状态管理库,例如Redux和MobX(都使用不同的策略来实现Context API)。
但是状态仍然位于FormComponent
上方(您仍在提升状态)。
const Context = React.createContext();
const ParentComponent = () => {
const contextState = useState(DEFAULT_STATE);
return (
<Context.Provider value={contextState}>
<FormComponent />
<AnotherComponent />
</Context.Provider>
);
};
const FormComponent = () => {
const [, setState] = useContext(Context);
// use setState
};
const AnotherComponent = () => {
const [state] = useContext(Context);
// valid state updated from FormComponent
};
答案 1 :(得分:0)
据我所知,在这些情况下要做的“正确的事情”是将状态上移一个级别,到您的“父级”组件中。
If you have a look at the Intro to React:
要从多个子组件收集数据,或使两个子组件相互通信,则需要在其父组件中声明共享状态。
“提升状态”在React应用程序中很常见,不需要引入像Redux或RxJS这样的状态管理解决方案。