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两者都不适用于我,我使用的是功能组件