React Native Context - TypeError: undefined is not an object (evaluating '_useContext.theme')

时间:2021-06-07 09:07:25

标签: reactjs react-native react-context

当我尝试在 App.js 中将 Context API 用于暗/亮模式时,我不断收到错误

Theme.js

import React, { useState } from "react";

export const ThemeContext = React.createContext();
//theme = light, dark

export const ThemeProvider = ({ children }) => {
    const [theme, setTheme] = useState("dark");

    const toggleTheme = () => {
        if (theme === "light") setTheme("dark");
        else setTheme("light");
    };

    return (
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};

App.js

import { ThemeContext, ThemeProvider } from "./app/utility/ThemeManager";

export default function App() {

    const { theme } = useContext(ThemeContext); // This is throwing the error

return (
  <ThemeProvider>
    ...//Rest of my app 
    //How I'd like to use my theme
      <StatusBar style={theme === "dark" ? "light" : "dark"} />
</ThemProvider>
);
};

我想了解为什么会抛出错误以及如何修复它?

提前致谢!

1 个答案:

答案 0 :(得分:0)

在 index.js 中导入 ThemeProvider

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import {  ThemeProvider } from "./Theme.js";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
  <ThemeProvider>
    <App />
  </ThemeProvider>,
  rootElement
);


在 App.js 中

import {ThemeContext} from "./Theme.js"
import StatusBar from './StatusBar';
import {useContext} from 'react'

export default function App() {

    const { theme } = useContext(ThemeContext); 

return (
  <>
  ..... Rest Of your Code
</>
);
};