首页 > 解决方案 > 在 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);

`*

标签: reactjs

解决方案


推荐阅读