在子组件中使用上下文 API 访问对象值

Access Object Values with Context API in Child Component

我将以下对象导出到另一个文件中:

info.js

export const info = {
    companyName: '',
    title: 'Some title',
    year: '',
};

我正在将此对象导入到我的 Context.js 中,如下所示:

信息Context.js

import React, { useState, createContext } from 'react';
import {info} from './info'
export const InfoContext = createContext();

export const InfoProvider = ({ children }) => {
  const [state, setState] = useState({
        ...info,
    });
    return (
        <InfoContext.Provider value={[state, setState]}>
            {children}
        </InfoContext.Provider>
    );
};

我想做的是从我的 App.js 中的状态访问对象值。 - 这是我尝试过但没有成功的方法:

App.js

import React from "react";
import { InfoProvider, InfoContext } from "./InfoContext";

export default function App() {
  return (
    <InfoProvider>
      <InfoContext.Consumer>
      {state => (
            <>
              <h1>{state.title}</h1>
            </>
          )}
      </InfoContext.Consumer>
      </InfoProvider>
  );
}

我显然遗漏了一些明显的东西。我已经尝试了一些事情,但我不确定是什么问题。我觉得这与从单独的文件访问我的对象有关。

此外,这里有一个包含上述代码的沙箱 link。任何帮助将不胜感激!

Code Sandbox

您将您的值作为数组传递给 Provider,但在 Consumer 上您希望它是一个对象。

您需要传递一个对象:

<InfoContext.Provider value={{state, setState}}>

另外你用错了Consumer。作为回调,它需要整个 value 您在 Provider 中传递的内容,而不是状态:

<InfoContext.Consumer>
  {(value) => (
    <>
      <h1>{value.state.title}</h1>
    </>
  )}
</InfoContext.Consumer>

或使用解构赋值:

<InfoContext.Consumer>
  {({state}) => (
    <>
      <h1>{state.title}</h1>
    </>
  )}
</InfoContext.Consumer>

然后你可以使用 value.setState({...}) 例如。等。但是请注意,像这样更新状态是一种不好的做法。

Code Sandbox