【问题标题】:How to access state from an handler on nextjs?如何从 nextjs 上的处理程序访问状态?
【发布时间】:2020-06-16 08:10:18
【问题描述】:

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

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

未处理的拒绝(TypeError):这是未定义的

代码如下:

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)

【问题讨论】:

    标签: javascript reactjs react-router next.js


    【解决方案1】:

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

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

    handleRouteChange = (url) => {
    
    // or
    
    Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))
    

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 2019-09-13
      • 2019-03-13
      • 2012-08-11
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多