javascript - React-router v4 this.props.history.push(...) 不起作用

标签 javascript reactjs react-redux react-router

我正在尝试使用 this.props.history.push(..) 以编程方式进行路由,但它似乎不起作用。

这是路由器:

import {
 BrowserRouter as Router,
 Route
} from 'react-router-dom';

<Router>
 <Route path="/customers/" exact component={CustomersList} />
 <Route path="/customers/:id" exact component="{Customer} />
</Router>

在 CustomerList 中,呈现客户列表。单击客户 (li) 应将应用程序路由至客户:

import { withRouter } from 'react-router'

class Customers extends Component {
  static propTypes = {
    history: PropTypes.object.isRequired
  }

 handleCustomerClick(customer) {
   this.props.history.push(`/customers/${customer.id}`);
 }

 render() {
   return(
    <ul>
      { this.props.customers.map((c) =>
        <li onClick={() => this.handleCustomerClick(c)} key={c.id}>
          {c.name}
        </li> 
    </ul>
  )

 }
}

//connect to redux to get customers

CustomersList = withRouter(CustomersList);
export default CustomersList;

该代码是部分的,但完美地说明了情况。 发生的情况是,浏览器的地址栏相应地更改为history.push(..),但 View 没有更新,Customer 组件没有渲染,CustomersList 仍然存在。有什么想法吗?

最佳答案

所以我来到这个问题希望得到答案,但没有成功。我用过

const { history } = this.props;
history.push("/thePath")

在同一个项目中,它按预期工作。 经过进一步的实验和一些比较和对比,我意识到如果在嵌套组件中调用此代码,将不会运行。因此只有渲染后的页面组件才能调用该函数才能正常工作。

查找工作沙箱 here

  • 历史记录:v4.7.2
  • react :v16.0.0
  • react-dom:v16.0.0
  • react 路由器-dom: v4.2.2

关于javascript - React-router v4 this.props.history.push(...) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312437/

相关文章:

javascript - Redux React-Native(在 react-redux 中使用 useSelector 与使用 connect 有什么区别?)

javascript - 是否有任何 IDE/IDE 插件支持 JavaScript CommonJS 模块?

javascript - 为什么在 CSS 中应用过渡时 jQuery 的 .fadeOut() 和 .fadeIn() 停止工作

javascript - 在node-express应用程序中使用node-mysql建立共享连接

javascript - 如何使用javascript计算textarea中输入字符的数量?

reactjs - 为什么编辑器字段不以 react-hook-form 呈现最近的数据

javascript - 以编程方式确定初始页面包大小

reactjs - 如何更改 NextJS 13 中服务器操作的状态?

javascript - react -JS : Access a child's method through HOC wrapper

javascript - removeTodo 操作不起作用,无法弄清楚,但我知道这是一个错误