如何从 nextjs 上的处理程序访问状态?

How to access state from an handler on nextjs?

我有一个自定义应用程序 (_app) 定义的处理程序,挂接到 routeChangeStart 事件。

处理程序应分析新路径并将一些结果存储在状态变量中。 处理程序是 class 成员,但它抛出错误:

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)

该函数是一个 class 成员,但 this 取决于函数被 调用的上下文 而不是 声明的。您正在将函数引用传递给将从其他地方调用它的侦听器,这意味着 this 将不再引用 class。

您必须手动将其绑定到 this,或者将其设为箭头函数。

handleRouteChange = (url) => {

// or

Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))