gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:24:36 25 4
gpt4 key购买 nike

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

最佳答案

您可以使用此代码

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页面将刷新。

关于javascript - React-router - 通过 history.push() 导航刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53963060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com