【问题标题】:React Router passing params to browserHistory from table rowReact Router 将参数从表行传递给 browserHistory
【发布时间】:2016-10-20 19:05:28
【问题描述】:

我正在实现 React Router,以便在单击任何表行(每一行都是用户/客户)时从搜索结果表链接到单独的配置文件组件。尝试使用Link 格式化表格是一场噩梦,因此我在每个表格行的onClick 处理程序中使用browserHistory.push()

问题:我需要根据单击的唯一行来呈现配置文件,并且我尝试将参数传递给 browserHistory,但运气为零。要么没有找到该组件,要么它只是访问了/tools/customer-lookup/profile

编辑:更新为添加一个处理函数,然后调用browserHistory.push()

路由器设置:

<Provider store={Store}>
    <Router history={browserHistory}>
        <Route path="/tools/customer-lookup" component={CustomerLookupApp} />
        <Route path="/tools/customer-lookup/profile/:id" component={CustomerProfile} />
    </Router>
</Provider>

表格行:(没有将{ id } 传递给browserHistory.push()

constructor(props) {
  super(props);

  this.pushToUrl = this.pushToUrl.bind(this);
  this.state = {
    selectedRow: []
  };
};

render() {
    let tableData = this.props.data.map(customer => {
      return (
        <tr onClick={this.pushToUrl(`/tools/customer-lookup/profile/${customer.address}`)} id="customer-data-row">
          <td>{customer.firstname}</td>
          <td>{customer.lastname}</td>
          <td>{customer.birthdate}</td>
          <td>{customer.city}</td>
          <td>{customer.state}</td>
          <td>{customer.address}</td>
        </tr>
      );
    });

pushToUrl(url) {
    console.log(url);
  }

tronClick 处理程序似乎对每一行数据都调用一次,这是零意义。以下是来自onClick 的处理程序的控制台日志:

【问题讨论】:

  • 在您的 中,为什么不用客户的 id 填充推送 url? onClick={browserHistory.push(`/tools/customer-lookup/profile/${customer.id}`)}
  • 好吧,当它试图访问数千名用户的每个唯一个人资料网址时,我的浏览器崩溃了......
  • 我很抱歉。修改它,以便您有一个处理程序,您可以在其中将 URL 传递给单击该函数时将执行的函数。我会发布一个例子
  • 哦,我明白了。因此,您需要传递对函数的引用。您实际上是在加载该函数时调用它来解释您的行为。 onClick={this.pushToUrl}onClick={this.pushToUrl()} 之间存在差异 请注意,在我的示例中,我调用了 .bind() 以正确绑定到正确的上下文并适当地传递参数,但在用户实际单击之前它不会执行。
  • 这很有趣。我一直在努力确保我的绑定在构造函数方法中,但你是绝对正确的。现在就像一个魅力。谢谢。

标签: javascript reactjs react-router


【解决方案1】:

您可以按照这些思路做一些事情。传递您打算导航到的网址。

goTo(url) {
    browserHistory.push(url)
}

render() {
    let tableData = this.props.data.map(customer => {
      return (
        <tr onClick={this.goTo.bind(this, `/tools/customer-lookup/profile/${customer.id}`)} id="customer-data-row">
          <td>{customer.firstname}</td>
          <td>{customer.lastname}</td>
          <td>{customer.birthdate}</td>
          <td>{customer.city}</td>
          <td>{customer.state}</td>
          <td>{customer.address}</td>
        </tr>
      );
    });

【讨论】:

  • 不走运,浏览器仍然崩溃。这很有趣,因为好像browserHistory 在页面加载时被调用,而不是在单击表格行时被调用。不过,我看不出为什么会这样。
  • 嗯,这很奇怪。我刚刚用 hashHistory 试了一下,效果很好。因此,尽管您将 browserHistory.push() 移动到方法中,但它仍在执行?你的代码现在是什么样子的?
  • 是的。就好像onClick 处理程序在表格呈现时被触发。我用 console.log 替换了 browserHistory 方法。我会发一张图片。
猜你喜欢
相关资源
最近更新 更多
热门标签