简体   繁体   English

将父级 state 传递给子级并将相同的 state 传回给父级

[英]Passing parent state to child and passing this same state back to parent

I have 2 react components X and Y. X holds state which is calculated through different types of logic and through user input.我有 2 个反应组件 X 和 Y。X 包含 state,它是通过不同类型的逻辑和用户输入计算的。 Users can click on a button in X which will unmount X and render Y. Now there also exists a button on Y which when clicked unmounts Y and renders X again, however X no longer has its state because it was lost when the component was unmounted when we first rendered Y. How can I ensure that X "holds" onto its state even when it gets unmounted?用户可以单击 X 中的一个按钮,这将卸载 X 并呈现 Y。现在 Y 上也存在一个按钮,当单击该按钮时,它会卸载 Y 并再次呈现 X,但是 X 不再具有其 state,因为当组件被卸载时它丢失了当我们第一次渲染 Y 时。如何确保 X 即使在卸载时也“保持”在其 state 上?

I've tried passing X's state as a prop to Y, but I'm not sure if I can pass this prop on Y back to X when Y unmounts?我已经尝试将 X 的 state 作为道具传递给 Y,但我不确定当 Y 卸载时我是否可以将 Y 上的这个道具传回给 X?

For all the state that needs to be accessed through both X and Y, initialize it in a parent component of both X and Y, then pass the state and its setters down to both.对于所有需要通过 X 和 Y 访问的 state,在 X 和 Y 的父组件中初始化它,然后将 state 及其 setter 传递给两者。 For example:例如:

const App = () => {
  const [showY, setShowY] = useState(false);
  const [persistentXState, setPersistentXState] = useState('');
  return showY
    ? <Y {...{ setShowY }} />
    : <X {...{ setShowY, persistentXState, setPersistentXState }} />;
};

This way, X can use its persistentXState prop and call setPersistentXState, and it'll persist even after setShowY gets called to unmount X and show Y again.这样,X 可以使用它的 persistentXState prop 并调用 setPersistentXState,即使在调用setShowY卸载 X 并再次显示 Y 之后它也会持续存在。

Yes, this is a classic case of lifting state up .是的,这是将 state 举起来的经典案例。 You absolutely can pass state up from Y using callbacks and setting it in the state of the parent.您绝对可以使用回调从 Y 向上传递 state 并将其设置在父级的 state 中。 Then pass it to Y again.然后再传给Y。

There is another trick, but it keeps both in memory so might not be the best: you can display: none using CSS instead of unmounting, which means it's there but the user just can't see it.还有另一个技巧,但它会将两者都保留在 memory 中,因此可能不是最好的:您可以使用 CSS display: none ,而不是卸载,这意味着它在那里,但用户看不到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM