React-router v4 this.props.history.push(...) 不工作 [英] React-router v4 this.props.history.push(...) not working

查看:21
本文介绍了React-router 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
  • 反应域:v16.0.0
  • react-router-dom:v4.2.2

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

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