我正在使用Next.js框架(v5)开发I18n模块。为了在用户的默认语言上显示UI,我正在试图弄清楚该语言是什么。从浏览器解析语言是“相当简单”的,但是我很难弄清楚如何在服务器端做到这一点,同时为包装我的Page的HOC提供该值,以便我可以在其中指定请求headers使用的语言环境,以便以该语言获取内容。我想出了如何在accept-language中使用pages/_documents.js标头从服务器解析用户的语言: static getInitialProps(props) { const { req, res, renderPage, isServer = false } = props; const cookies = new Cookies(); if (isServer) { const headers = req.headers; const acceptedUserLanguages = acceptLanguageParser.parse(headers['accept-language']); const mostPreferredLanguage = get(acceptedUserLanguages, '[0]', {}); // {code: 'en', region: 'GB'}这很好。但是,我需要在包装页面组件的HOC中访问此mostPreferredLanguage,而且我真的不知道该怎么做,因为HOC代码是在getInitialProps函数之前执行的。据我所知,我无法从HOC本身访问req.headers。HOC实施:export default withData( compose( withRedux(configureStore), withLoanAdvisor, graphql(institutionPagesData, { options: (props) => { return { context: { headers: { 'gcms-locale': 'FR', // How do I universally get the user language here? I don't have access to request.headers there 'gcms-locale-no-default': false }, }, }; }, }), )(SchoolPage));潜在的解决方案Redux我一直在考虑使用Redux。我尝试实现它,但由于无法在服务器端使用Redux而被阻止。Redux的想法是使用getInitialProps解析语言并将其存储在redux中,然后在运行graphql() HOC查询之前我将连接到商店,因此使该语言在 HOC,以便我可以使用正确的标头运行查询。但是如上所述,Redux在服务器端不可用,尝试通过props对其进行初始化会使服务器崩溃。见https://github.com/zeit/next.js/issues/3990#issuecomment-372159451饼干我也尝试使用cookie,但是虽然我成功地从两个浏览器/服务器读取cookie,但无法在graphql _document.js函数内的服务器端写入它们。我不知道为什么,而existing examples并没有帮助我。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您可以从HOC访问getInitialProps-getInitialProps的限制照常适用(没有子组件,只有pages),但这是很常见的模式,例如:const withSize = (WrappedComponent) => { return class extends React.Component { static async getInitialProps({ req }) { const ua = req ? req.headers['user-agent'] : navigator.userAgent; const userAgent = uaParser(ua); return { userAgent }; } // ... implementation render() { // userAgent meant to be removed from props const { userAgent, ...props } = this.props || {}; return ( <WrappedComponent {...props} {...this.state} isMobile={this.state.windowWidth <= deviceWidth.mobile} isTablet={this.state.windowWidth <= deviceWidth.tablet} /> ); } };};有关更多示例,请参见nextjs的示例。 https://github.com/zeit/next.js/blob/3e51ddb8af55b6438aa3aeb382081b9a1c86f325/examples/with-lingui/components/withLang.js。(如果要在HOC包装的组件中使用hoistNonReactStatics,请不要忘记使用getInitialProps。) (adsbygoogle = window.adsbygoogle || []).push({});
09-10 12:23
查看更多