props.history 使用 withRouter 时未找到

props.history not found when using withRouter

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

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

当我点击每个 select 选项时,我被告知道具未定义,我在这里错过了什么?

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);

我认为您需要将 handleChange 方法显式绑定到 this。尝试向 Dropdown class 添加构造函数,例如:

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

至少他们在此处的文档中是这样做的:https://reactjs.org/docs/handling-events.html

我想你忘了绑定你的 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}`);
}