繁体   English   中英

React.js 上下文提供者没有将提供的值传递给 useContext

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

问题:

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

我的发现:

  • ImageContextProvider中的 State images具有正确的值(第一个初始声明并更改获取的数据)。
  • 更改 state 的初始值(不是上下文),可在ImageContextProvider中找到,并没有更改useContext挂钩的 output -> 仍然只是发送了初始上下文值
  • 将所有内容放入一个文件(以避免某种错误的引用)也不能解决问题
  • 在堆栈溢出上没有发现任何类似的问题

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;

可视化器.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

暂无
暂无

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

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