反应路由器v4 this.props.history.push(...)不起作用 [英] React-router v4 this.props.history.push(...) not working

查看:441
本文介绍了反应路由器v4 this.props.history.push(...)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用this.props.history.push(..)以编程方式进行路由,但似乎无法正常工作.

I'm trying to route programatically using this.props.history.push(..) but it doesn't seem to work.

这是路由器:

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)可以将申请路线转到客户:

In CustomerList, a list of customers is rendered. Clicking on a customer (li) should make the application route to Customer:

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(..),但视图未更新,Customer组件未呈现,CustomersList仍然存在.有什么想法吗?

The code is partial but illustrates perfectly the situation. What happens is that the browser's address bar changes accordingly to history.push(..), but the view does not update, Customer component is not rendered and CustomersList is still there. Any ideas?

推荐答案

所以我来到这个问题,希望得到答案,但无济于事.我用过

So I came to this question hoping for an answer but to no avail. I have used

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

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

In the same project and it worked as expected. Upon further experimentation and some comparing and contrasting, I realized that this code will not run if it is called within the nested component. Therefore only the rendered page component can call this function for it to work properly.

找到工作沙箱此处

  • 历史记录:v4.7.2
  • 反应:v16.0.0
  • react-dom:v16.0.0
  • react-router-dom: v4.2.2
  • history: v4.7.2
  • react: v16.0.0
  • react-dom: v16.0.0
  • react-router-dom: v4.2.2

这篇关于反应路由器v4 this.props.history.push(...)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆