React-router - 通过 history.push() 导航刷新页面

React-router - navigating through history.push() refreshes the page

当我使用 <Link /> 组件时,导航会在没有页面刷新的情况下顺利进行,但是当我尝试通过 history.push() 导航时(即在提交表单时),页面会刷新。如何防止 history.push() 进行刷新?这是我的代码:

import React from 'react';
import {withRouter} from 'react-router-dom';
import qs from 'query-string';

class SearchBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  handleSubmit(e) {
    this.props.history.push('?' + qs.stringify({search: this.state.value}));
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div className="searchbox">
          <input
            type="text"
            name="search"
            value={this.state.value}
            onChange={this.handleChange}
            placeholder="Search..."
          />
        </div>
      </form>
    );
  }
}

export default withRouter(SearchBox);

e.preventDefault() 作为 handleSubmit() 函数中的第一个语句,然后将 url 推送到历史记录。

您可以使用此代码

import { createBrowserHistory } from "history";

// ... Your codes

handleSubmit(e) {
  const historyBrowser = createBrowserHistory({
        basename: process.env.PUBLIC_URL,
        forceRefresh: false,
      });
  historyBrowser.push('?' + qs.stringify({search: this.state.value}));
  e.preventDefault();
}

如果您设置 forceRefresh: true 页面将刷新。

根据@ic3b3rg 的评论: 必须在 push:

的参数中包含路径
  handleSubmit(e) {
    this.props.history.push('/?' + qs.stringify({search: this.state.value}));
    e.preventDefault();
  }