【发布时间】: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