这是上下文第一次给我带来问题。我尝试了以下示例和教程,但没有一个起作用。任何人都可以针对我正在做的事情提出任何建议,因为我的代码和其他人的上下文代码到目前为止还没有奏效。
context.js
import React, { Component } from 'react'
import { createContext } from 'react'
export const DataContext = createContext();
class DataContextProvider extends Component {
constructor(props) {
super(props)
this.state = {
users:[],
messages:[]
}
}
addUser = (user) => {
this.setState({
users:[...this.state.users,user]
})
}
addMessage = (message) => {
this.setState({
messages:[...this.state.messages,message]
})
}
render() {
const {addUser,addMessage} = this;
return (
<DataContext.Provider value={{
...this.state,
addUser,
addMessage
}}>
{this.props.children}
</DataContext.Provider>
)
}
}
export default DataContextProvider;
app.js
import DataContextProvider from './Components/context';
function App() {
return (
<ThemeProvider theme={theme}>
<DataContextProvider>
<div className="App">
<Header />
<Main />
</div>
</DataContextProvider>
</ThemeProvider>
);
}
Content.js
const data = useContext(DataContextProvider);
console.log(data) // returns undefined