我有一个由自定义应用 (_app
) 定义的处理程序, Hook 到 routeChangeStart
事件。
处理程序应该分析新路径并将一些结果存储在状态变量中。 处理程序是类成员,但它抛出错误:
Unhandled Rejection (TypeError): this is undefined
代码如下:
import App from 'next/app';
import Router from 'next/router'
import { withRouter } from 'next/router'
import MyAppContext from '~/components/MyAppContext';
class MyApp extends App {
state = {
language: null
};
getCurrentLanguage(url){
...
}
handleRouteChange(url){
console.log('App is changing to: ', url)
this.setState ( //throws: Unhandled Rejection (TypeError): this is undefined
{language: this.getCurrentLanguage(url)}
)
}
componentDidMount = () => {
this.setState({language: this.getCurrentLanguage()})
Router.events.on('routeChangeStart', this.handleRouteChange)
};
render() {
const { Component, pageProps } = this.props;
return (
<MyAppContext.Provider value={{ language: this.state.language }}>
<Component {...pageProps} />
</MyAppContext.Provider>
);
}
}
export default withRouter(MyApp)
最佳答案
该函数是类成员,但 this
取决于该函数调用而不是声明的上下文。您将函数引用传递给监听器,监听器将从其他地方调用它,这意味着 this
将不再引用该类。
您必须手动将其绑定(bind)到 this
,或者将其设为箭头函数。
handleRouteChange = (url) => {
// or
Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))
关于javascript - 如何从 nextjs 上的处理程序访问状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60515806/