Reactjs 使用withRouter时未找到props.history

Reactjs 使用withRouter时未找到props.history,reactjs,react-router,higher-order-components,Reactjs,React Router,Higher Order Components,我正在尝试设置一个简单的下拉列表,当用户从选择菜单中选择不同的项目时,它将启用不同的路由 我已经用HOC withRouter()包装了我的组件,我认为它将从路由器传递所有道具 当我点击每个选择选项时,我被告知道具是未定义的,我在这里遗漏了什么 import React, { Component } from "react"; import { withRouter } from "react-router-dom"; class Dropdown extends Component {

我正在尝试设置一个简单的下拉列表,当用户从选择菜单中选择不同的项目时,它将启用不同的路由

我已经用HOC withRouter()包装了我的组件,我认为它将从路由器传递所有道具

当我点击每个选择选项时,我被告知道具是未定义的,我在这里遗漏了什么

import React, { Component } from "react";
import { withRouter } from "react-router-dom";

class Dropdown extends Component {
  handleChange(e) {
    this.props.history.push(`/${e.target.value}`);
  }

  render() {
    return (
      <>
        <select name="" className="Dropdown" onChange={this.handleChange}>
          <option value="top">Top</option>
          <option value="new">New</option>

          <option value="best">Best</option>
        </select>
      </>
    );
  }
}

export default withRouter(Dropdown);
import React,{Component}来自“React”;
从“react router dom”导入{withRouter};
类下拉列表扩展组件{
手变(e){
this.props.history.push(`/${e.target.value}`);
}
render(){
返回(
顶部
新的
最好的
);
}
}
使用路由器导出默认值(下拉菜单);

我认为您需要将您的
handleChange
方法显式绑定到
this
。尝试将构造函数添加到
下拉列表中,如:

  constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this);
  }

至少在这里的文档中是这样做的:

我想你忘了绑定你的
handleChange
函数,这样你就可以像这样在状态之后绑定函数了

 constructor(props) {
    super(props)
    this.handleChange = this.handleChange.bind(this);
  }
或者你可以这样做

 <select name="" className="Dropdown" onChange={this.handleChange.bind(this)}>
handleChange =  async e => {
    this.props.history.push(`/${e.target.value}`);
}