reactjs - 在 react-router-dom 中来回浏览器 ^5
问题描述
我是反应新手。
我正在使用反应路由器 dom 开发照片 Web 应用程序。我的应用程序有导航链接和搜索表单。我希望能够在我的网络应用程序中使用浏览器的后退和前进按钮。
到目前为止,如果我单击浏览器后退按钮,则 url 会更改为以前访问过的正确路由,但我的路由不会更改为匹配 url。
我尝试了几种方法都没有运气。
如何使用 react createBrowserHistory (或任何其他方法)推送 url?
这是我到目前为止所做的详细信息的回购https://github.com/Akhaled19/unit7_react-gallery-app
首先我安装,导入反应历史库(这是导入到我所有的路线) npm install --save react-history import { BrowserHistory } from 'react-history' const history = BrowserHistory();
然后我将此代码添加到我的 app.js
*<BrowserRouter history={history}>
<switch>
//listed routes here..
</switch
</BrowserRouter>*
我首先想在我的搜索表单路由上对此进行测试,所以我在那里添加了以下代码(如果它有效,我将添加到我的 app.js 文件中。为什么?因为我有一些浏览器的必要代码,并且前进按钮开始工作。) *` class SearchForm extends Component{ state = { searchText: '', query: '' }
componentDidMount() {
this.setQuery();
}
componentDidUpdate(prevProp) {
if(prevProp.match.params.query !== this.props.match.params.query) {
this.setQuery();
}
}
setQuery = () => {
const { query = ""} = this.props.match.params;
this.setState({
searchText: query, query
});
}
//This methods handles updating the searchText state when a user types.
onSearchChange = e => {
this.setState({
searchText: e.target.value
})
}
//This method handle what to do when a user hits submit:
//It grabs the query value to create a route path with it
//push that route to the current route
handleSubmit = e => {
e.preventDefault();
let searchedQuery = this.state.value;
let path = `/search/${searchedQuery}`;
history.push(path);
this.props.onSearch(searchedQuery);
e.currentTarget.reset();
}
render() {
return(
<form className='search-form' onSubmit {this.handleSubmit} >
<input
type='search'
onChange={this.onSearchChange}
name='search'
ref={ (input) => this.query = input }
placeholder='Search...'
required />
</form>
);
};
}
export default withRouter(SearchForm);
`*
解决方案
推荐阅读
- python - 如何将两个数据集与 BusinessID 合并并获得最终数据集?
- sql - 为什么“解释分析”这个查询很快完成(显示并行计划),而在没有“解释分析”的情况下运行实际查询却没有?
- ios - navigationBarTitle / displayMode 在 iOS 13.2 和 13.3 上崩溃
- reactjs - 如何将数据传递给由重定向加载的单独组件?
- automapper - 在 .NET CORE 2.2 Web API 应用程序中配置 AutoMapper
- powershell - Powershell CSOM - 更新项目部门查找字段值
- trains - 火车:重用以前的任务ID
- wordpress - 将自定义查询附加到 Wordpress 特定菜单
- http - 为什么 HTTP GET 和 POST 请求以不同的方式(正文与 URI)向服务器传递参数?
- ios - 在 UITableView 中滚动时防止 UISearchBar 隐藏(滚动时保持 UISearchBar 显示)-Swift,Xcode