gpt4 book ai didi

javascript - 如何将上下文传播到路由器组件。 react 堆

转载 作者:行者123 更新时间:2023-11-29 23:30:37 25 4
gpt4 key购买 nike

我想在我的 reactjs 应用程序中将登录用户的数据设为全局。我的应用代码:

class App extends Component {
getChildContext = () => {
return {
user: {
name: 'username',
email: 'email@rmail.com'
}
}
}

render() {
return (
<Router>
<div>
<Route exact path='/game' component={Game} />
<Route exact path='/singup' component={Singup} />
</div>
</Router>
);
}

App.childContextTypes = {
user: PropTypes.object
};

在 Game 组件中,我尝试通过 this.context.user 使用,但我得到 undefined

我可以将上下文传播到 Router 组件吗?

最佳答案

By adding childContextTypes and getChildContext to the context provider, React passes the information down automatically and any component in the subtree can access it by defining contextTypes. If contextTypes is not defined, then context will be an empty object.

确保您已经在Game 组件上定义了contextTypes

Game.contextTypes = {
user: PropTypes.object
};

https://reactjs.org/docs/context.html

关于javascript - 如何将上下文传播到路由器组件。 react 堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com