React Router passing params to browserHistory from table row

时间:2016-10-20 19:05:29

标签: javascript reactjs react-router

I'm implementing React Router to link from a table of search results to a separate Profile component upon click of any table row (each row would be a user/customer). Trying to format a table with Link is nightmarish, so I'm using browserHistory.push() within an onClick handler on each table row.

Problem: I need to render the Profile based on the unique row clicked and I've tried passing params to browserHistory with zero luck. Either the component isn't found or it just visits /tools/customer-lookup/profile.

EDIT: Updated to add a handler function which then calls browserHistory.push()

Router Setup:

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

Table Rows: (without an { id } being passed to 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);
  }

The tr onClick handler appears to be being called once for every row of data, which makes zero sense. Here are console.logs of the handler from onClick:

enter image description here

1 个答案:

答案 0 :(得分:2)

You can do something along these lines. Pass the url you intend to navigate to.

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