TypeError:无法解构“Object(...)(...)”的属性“Provider”,因为它未定义
2020-11-25
1430
我尝试使用 useContext,但不断出现错误。这是我的配置文件
import React from 'react'
export const ConfigurationContext = React.createContext()
export default ConfigurationContext
这是我的 App.js
import './App.css';
import React,{Fragment} from 'react'
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import Header from './components/header/header.js'
import Footer from './components/footer/footer.js'
import {Menu} from './components/menu/menu.js'
import {Home, About} from './components/home/home.js';
import {Editor} from './components/Editor/editor.js'
import ConfigurationContext from './contexts/configuration';
import {useContext} from 'react'
export const config = {
user: {
fullname: "Jim Brown",
id: 345
}
}
function App() {
const {Provider, Consumer} = useContext(ConfigurationContext)
Provider.value = config
return (
<Fragment>
<Header></Header>
<Router>
<Menu></Menu>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/contact" >
<Editor />
</Route>
<Route exact path="/about" component={About} />
</Switch>
</Router>
<Footer></Footer>
</Fragment>
);
}
export default App;
这是我收到的错误: TypeError:无法解构“Object(...)(...)”的属性“Provider”,因为它未定义。 App src/App.js:28 25 | 26 | function App() { 27 |
28 | const {Provider, Consumer} = useContext(ConfigurationContext) 29 | 30 | Provider.value = config 31 | View compiled ▶ 17 stack frames were collapsed.
2个回答
问题出在这里
const { Provider, Consumer} = useContext(ConfigurationContext) 👈🏻Returns context
value
not Provider Context Object
你可以这样尝试。这是 工作演示
import React, { createContext, useContext, useState, useEffect } from "react";
import { render } from "react-dom";
// Move to seperate file if you want to
const ConfigurationContext = createContext(null); // You can pass default context as well
// Button.js
const Button = () => {
const { config, setConfig } = useContext(ConfigurationContext);
useEffect(() => {
console.info("config.fullname changed:", config.fullname);
}, [config]);
const changeUserName = () => {
config.user.fullname = 'New User'
setConfig({ ...config });
};
return (
<button onClick={changeUserName}>
Change User Name
</button>
);
};
const defalutConfig = {
user: {
fullname: "Jim Brown",
id: 345
}
}
const App = () => {
const [config, setConfig] = useState(defalutConfig);
return (
<ConfigurationContext.Provider value={{ config, setConfig }}>
<h1>React Context Demo</h1>
<h3>
User in Parent: { config.user.fullname }
</h3>
<Button />
</ConfigurationContext.Provider>
);
};
render(<App />, document.getElementById("root"));
Naren
2020-11-25
尝试使用括号导入:
import ConfigurationContext from './contexts/configuration';
jozinho22
2022-03-07