访问上下文值时变得不确定

时间:2019-07-23 17:07:46

标签: reactjs react-hooks react-context

尝试从组件访问undefined时,我一直在获取values。这是我的提供程序文件内容:

import React from "react";
import { FlyToInterpolator } from "react-map-gl";

export const MapContext = React.createContext();
export function MapProvider(props) {
  const [viewport, setViewport] = React.useState(INITIAL_STATE);

  const onLoad = () => {
    setViewport(DRC_MAP);
  };
  return (
    <MapContext.Provider
      value={{
        viewport,
        setViewport,
        onLoad
      }}
      {...props}
    />
  );
}

export const { Consumer: MapConsumer } = MapContext;

export const withMap = Component => props => {
  return (
    <MapConsumer>{value => <Component map={value} {...props} />}</MapConsumer>
  );
};

// this is what state gets initialised as
const INITIAL_STATE = {
  height: "100vh",
  width: "100%",
  longitude: 23.071374,
  latitude: -3.6116245,
  zoom: 1.33
};

const DRC_MAP = {
  longitude: 23.656,
  latitude: -2.88,
  zoom: 4,
  transitionDuration: 3000,
  transitionInterpolator: new FlyToInterpolator(),
  transitionEasing: t => t * (2 - t)
};

因此,当我尝试使用viewport或其他任何定义的values时,我会得到undefined。这是我的Map组件,正在使用上述代码。

import React, { useContext } from "react";
import ReactMapGL from "react-map-gl";
import { MapContext } from "./contexts/MapProvider";

const MAPBOX_TOKEN ="secret"
const mapStyle = "mapbox://styles/jlmbaka/cjvf1uy761fo41fp8ksoil15x";

export default function Map() {
  const { viewport, setViewport, onLoad } = useContext(MapContext);

  return (
    <ReactMapGL
      mapboxApiAccessToken={MAPBOX_TOKEN}
      mapStyle={mapStyle}
      onViewportChange={nextViewport => setViewport(nextViewport)}
      onLoad={onLoad}
      ref={ref => (window.mapRef = ref && ref.getMap())}
      {...viewport}
    />
  );
}

我已经阅读了几个与我的问题相似的问题,但是没有一个适合我的情况。在这里,它们是: Context value undefined in React React context state property is undefined

1 个答案:

答案 0 :(得分:0)

您做了一个Context.Provider

export function MapProvider({ children, ...props }) {
  const [viewport, setViewport] = React.useState(INITIAL_STATE);

  const onLoad = () => {
    setViewport(DRC_MAP);
  };

  return (
    <MapContext.Provider
      value={{
        viewport,
        setViewport,
        onLoad
      }}
      {...props}
    >
      {children}           // <-- Children are consumers
    </MapContext.Provider>
  );
}

但是您没有使用上下文:

// Somewhere in the code you need to consume its context
function Consumer() {
  return (
    <MapProvider>
      <Map />
    </MapProvider>
  );
}

然后useContext将有效:

export default function Map() {
  // Child of MapContext.Provider,
  // so it can consume the context.
  const { viewport, setViewport, onLoad } = useContext(MapContext);
  ...
}