【发布时间】:2018-09-27 23:34:24
【问题描述】:
我有一个类似
的 URL 结构foo.com/details/:id
并与它一起使用 ReactRouter。如果您搜索 ID '123',该组件会呈现来自数据库的特定信息并将 URL 更新为
foo.com/details/123
如果您搜索另一个 ID '456',则 URL 会更新为
foo.com/details/456
this.props.history.push(${this.state.id});
简而言之 - 组件重新渲染。如果您重新加载或直接转到带有 URL 的 ID,则该参数将按预期工作。这是我的问题:如果您在浏览器中按下后退按钮,URL 会正确更新 (456 => 123),但组件不会重新呈现。
如何在 URL 参数更改时强制组件重新呈现?
编辑:更多代码
在构造函数中:
if (this.props.match.params.id !== undefined) {
this.state.id = this.props.match.params.id;
this.getData(this.state.id)
}
在课堂上:
<form onSubmit={this.handleSubmit}>
<input type="text" className="form-control mx-sm-3 mb-2" placeholder="Enter ID"value=
{this.state.id} onChange={this.handleChange}/>
<input type="submit" value="Search" className="btn btn-primary mb-2"/>
</form>
handleChange(event) {
this.setState({id: event.target.value})
}
handleSubmit(event) {
this.props.history.push(`${this.state.id}`);
this.getData(this.state.id);
event.preventDefault();
}
【问题讨论】:
标签: reactjs react-router