英文:
React context undefined in child component
问题
以下是你要翻译的代码部分:
I'm new in react and I try to use a context for passing current username, I follow the tutorial, but it seems that my context is always undefined, can someone explain what I'm doing wrong?
const AppContext = React.createContext({});
class App extends React.Component {
componentDidMount() {
this.setState({
User: {
Username: "Guest",
UserType: {
Description: "Guest"
}
}
});
}
render() {
return (<div className="App">
<AppContext.Provider value={this.state}>
<Toolbar/>
<!--This work fine-->
<h3>{this.state.User.Username}</h3>
</AppContext.Provider>
</div>);
}
}
class Toolbar extends React.Component {
constructor(props, context) {
super(props);
}
render() {
return (
<header className="toolbar">
<!-- print the username -->
</header>
);
}
}
export default Toolbar;
你尝试过的解决方案:
-
<h3>{this.context.Username}</h3>
-
<h3>{this.context.User.Username}</h3>
-
this is something I found on internet, but it gives me "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined":
<AppContext.Consumer> {(value) => ( <p>Inside consumer {value}</p> )} </AppContext.Consumer>
英文:
I'm new in react and I try to use a context for passing current username, I follow the tutorial, but it seems that my context is always undefined, can someone explain what I'm doing wrong?
const AppContext = React.createContext({});
class App extends React.Component {
componentDidMount() {
this.setState({
User: {
Username: "Guest",
UserType: {
Description: "Guest"
}
}
});
}
render() {
return (<div className="App">
<AppContext.Provider value={this.state}>
<Toolbar/>
<!--This work fine-->
<h3>{this.state.User.Username}</h3>
</AppContext.Provider>
</div>);
}
}
class Toolbar extends React.Component {
constructor(props, context) {
super(props);
}
render() {
return (
<header className="toolbar">
<!-- print the username -->
</header>
);
}
}
export default Toolbar;
I tried these solutions:
-
<h3>{this.context.Username}</h3>
-
<h3>{this.context.User.Username}</h3>
-
this is something I found on internet, but it gives me "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined":
<AppContext.Consumer>
{(value) => (
<p>Inside consumer {value}</p>
)}
</AppContext.Consumer>
答案1
得分: 1
将 contextType 分配给读取上下文。
使用这个属性可以让您使用 this.context 消费最近的上下文类型的当前值。
class Toolbar extends React.Component {
static contextType = AppContext;
render() {
return (
<header className="toolbar">
<!-- 打印用户名 -->
</header>
)
}
}
英文:
Assign a contextType to read the context.
> Using this property lets you consume the nearest current value of that Context type using this.context.
class Toolbar extends React.Component {
static contextType = AppContext;
render() {
return (
<header className="toolbar">
<!-- print the username -->
</header>
)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论