Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React router-浏览历史记录。push()刷新页面_Javascript_Reactjs_React Router_React Router V4_History - Fatal编程技术网

Javascript React router-浏览历史记录。push()刷新页面

Javascript React router-浏览历史记录。push()刷新页面,javascript,reactjs,react-router,react-router-v4,history,Javascript,Reactjs,React Router,React Router V4,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

当我使用
组件时,导航会顺利进行,无需页面刷新,但当我尝试在
历史记录.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);
从“React”导入React;
从“react router dom”导入{withRouter};
从“查询字符串”导入qs;
类SearchBox扩展了React.Component{
建造师(道具){
超级(道具);
this.state={value:''};
this.handleChange=this.handleChange.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
手变(e){
this.setState({value:e.target.value});
}
handleSubmit(e){
this.props.history.push('?'+qs.stringify({search:this.state.value}));
e、 预防默认值();
}
render(){
返回(
);
}
}
使用路由器导出默认值(搜索框);

handleSubmit()
函数中生成
e.preventDefault()
第一条语句,然后将
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
页面将刷新。

两个建议:1。先执行
e.preventDefault()
2。在
push
参数中包括一个路径,例如
.push(“/?”+…)
建议2有效,谢谢@ic3b3rg两者都不适用于我,我使用的是功能组件