React-Router-浏览history.push()刷新页面

时间:2018-12-28 18:49:19

标签: javascript reactjs react-router react-router-v4 history

当我使用<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);

2 个答案:

答案 0 :(得分:0)

e.preventDefault()函数中使handleSubmit()成为第一条语句,然后将url推入历史记录。

答案 1 :(得分:0)

您可以使用此代码

def IsnonrepeatedRow(A):
  count = 0
  for i in range(len(A)):
    for x in range (i+1, len(A)):
      for j in range(len(A[0])):
        if A[i][j] // A[x][j] == 0:
         count += 1
      if count == len(A[0]):
        return True
      count = 0
return False

如果您设置了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(); } ,页面将会刷新。