如何确保在更新子状态时也更新父状态?



我有一个React应用程序的架构如下:

<GrandParentComponent>
<ParentComponent>
<ChildComponent>
</ParentComponent>
</GrandParentComponent>

子组件在其内部创建上下文,以便与所有内部组件共享。我有一个ref作为useCallback()<ParentComponent>传递到<ChildComponent>,以跟踪从<GrandparentComponent>传递的状态。

祖父母

const [isPlaying, setIsPlaying] = useState(false);
return (
<>
{ isPlaying ? "True" : "False" } 
<ParentComponent {...{isPlaying, setIsPlaying}}/>
</>
);

父母

const [button, setButton] = useState();
const handleRef = useCallback( current => {
if(current) {
setButton(current.button);
}
}, []);
useEffect(() => {
if(button) {
const callback = ({type}) => setIsPlaying(type === "play");
button.addEventListener("play", callback);
return () => {
button.removeEventListener("play", callback);
};
}
}, [button]);
return (
{ isPlaying ? "True" : "False" } 
<ChildRoot>
<Child ref={handleRef}/>
</ChildRoot>
); 

const export ChildRoot = ({children}) => {
return (
<ChildContext.Provider value={{
isOpen: true,
setIsOpen: () => {}
}}
/>
{children}
</ChildContext.Provider>
);
};

const export Child = ({}, forwardRef) => {
const ref = useRef();

useImperativeHandle(forwardRef, () => ({
get button() {
return ref.current();
}
})
});

由于某种原因,isPlaying的值只反映在<ParentComponent>中,而没有反映在<GrandParentComponent>中。我试过使用useContext(),但也没有解决这个问题。

我如何确保状态是一致的?

我通过将Child组件合并为一个组件并将其导出到Parent组件来修复此问题。

最新更新