使用Context API传递数据时值未定义

时间:2020-08-06 09:07:26

标签: javascript reactjs react-hooks react-context context-api

我正在尝试使用Context API将数据传递给子组件。从组件中获取值后,其值即为undefined

组件层次结构

  • 将数据传递到组件MockTableUsecasePane
  • MainContent -> MockTable
  • MainContent -> AddMock -> TabContent -> UsecasePane

=> MockContext.js

import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

export const MockContext = createContext();

// provider
export const MockProvider = (props) => {
  const [data, setData] = useState([]);
  
   // data fetch and setting the state

  return (
    <MockContext.Provider data={[data, setData]}>
      {props.children}
    </MockContext.Provider>
  );
};

  • 注意:我正在从API得到响应。

现在在MainContent中,组件封装如下:

// MainContent.js

import React from "react";
import { MockProvider } from "../MockContext";

const MainContent = () => {
  return (
    <MockProvider>
      <div>
        <CustomerTable />
        <AddMock />
        <MockTable />
      </div>
    </MockProvider>
  );
};

当我尝试获取MockTableUseCasePane中的数据时,值为undefined

// MockTable.js

import React, { useState, useEffect, useContext } from "react";
import { MockContext } from "./MockContext";

const MockTable = () => {

  const [data, setData] = useContext(MockContext);
  console.log(data);

  // rest of the code

}

请纠正我要去的地方:)

我也尝试从上下文中传递字符串,并在类似以下的组件中获取

return (
    <MockContext.Provider data={"Hello"}>
      {props.children}
    </MockContext.Provider>
  );

// in MockTable.js
const value = useContext(MockContext); ==> undefined

1 个答案:

答案 0 :(得分:3)

传递到Provider的正确道具是value不是 data。 (请参阅:Context.Provider


import React, { useState, useEffect, createContext } from "react";
import axios from "axios";

export const MockContext = createContext();

// provider
export const MockProvider = (props) => {
  const [data, setData] = useState([]);
  const fetchData = async () => {
    const response = await axios
      .get(config.App_URL.getAllRoute, {
        params: {
          customHostName: config.host,
          type: config.type,
        },
      })
      .catch((error) => {
        console.error(`Error in fetching the data ${error}`);
      });
    console.log(response.data);
    setData(response.data);
  };
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <MockContext.Provider value={[data, setData]}>
      {props.children}
    </MockContext.Provider>
  );
};