【问题标题】:HOCs, Context API and Next PagesHOC、上下文 API 和下一页
【发布时间】:2021-03-10 13:22:36
【问题描述】:
是否可以在下一页中使用带有上下文 api 的 Hoc?
我有一个由 SSR 生成的下一页,以及一个 HOC privateRoute 来验证此页面上的授权。但是对于每次访问,我们都有一个授权请求,它的声音让我觉得很麻烦。
我的想法是使用 contexApi 一次性获取数据,然后在 auth 私有路由上重复使用。
谁有一个最小的例子?
谢谢。
【问题讨论】:
标签:
server-side-rendering
react-context
high-order-component
【解决方案1】:
我找到了解决办法。
问题是在反应类组件中使用上下文。
mport React, { Component } from 'react'
import UserContext from './UserContext'
class HomePage extends Component {
static contextType = UserContext
componentDidMount() {
const user = this.context
console.log(user) // { name: 'Tania', loggedIn: true }
}
for more, see https://www.taniarascia.com/using-context-api-in-react/
render() {
return <div>{user.name}</div>
}
}