React.js 上下文提供程序不将提供的值传递给 useContext

React.js Context Provider does not pass provided values to useContext

问题:

我正在使用 useContext 挂钩通过 DOM 传递数据,但现在唯一传递的数据是来自 ImageContext 的初始值。

我的发现:

image_context.js

export const ImageContext = createContext({
    images: [],
    loading: true,
    setImages: () => {},
});


const ImageContextProvider = props => {
    const [images, setImages] = useState({
        images: [],
        loading: true
    }); // Array instead of object

    const fetchData = () => {
        imagesServices.loadImages().then((img) => {
            setImages({
                images: img,
                loading: false
            })
        })
    }

    useEffect(() => {
        fetchData();
    }, []);

    useDebugValue(images ?? 'loading...')
    let value = {images: images.images, loading: images.loading, setImages: setImages}
    return(
    <ImageContext.Provider value={value}>
        {props.children}
    </ImageContext.Provider>
    );
};

export default ImageContextProvider;

visualizer.js

const Visualizer = () => {
    return (
        <ImageContextProvider>
            <Canvas
                camera={{position:  new THREE.Vector3( 0, 0, -0.5 ), fov: 60}}>
                <ambientLight intensity={0.3}/>
                <group>
                    <ImageGroup />
                </group>
                <OrbitControls enableZoom={false} enablePan={false}/>
            </Canvas>
        </ImageContextProvider>
    );
};

export default Visualizer;

image_group.js

const ImageGroup = (props) => {
    const {
        roomID = '0',
        ...restProps
    } = props;
    const {images, loading, setImages} = useContext(ImageContext);

    if (images.loading) return null

    return (
        <Suspense fallback={null}>
            {
                images.map((img) =>
                    (<ImagePlane key={img['imageID']} imgLink={img['imgLink']} position={img['position']}  aspectRatio={img['aspect_ratio']}/>)
                )
            }
        </Suspense>
    );
};

export default ImageGroup;

我的问题的解决方案是将 ImageContextProvider 放在 canvas 中。这是必要的,因为 canvas 中的元素使用不同的上下文,如下所述: https://github.com/pmndrs/react-three-fiber/blob/master/docs/API/hooks.mdx