如何解决ReactJS:表单提交后重定向而不刷新
我创建了一个表单,该表单在按下“提交”按钮后调用搜索功能。我希望搜索结果显示在另一个功能组件中(为此目的使用了React Context)。
但是,我遇到一个问题,无法在不刷新页面的情况下将其链接到另一条路线/yourstage/results
。如果刷新页面,则存储在state中的seachResult将消失。
import React,{ Fragment,useState,useEffect,useContext } from "react";
import { withRouter,Link } from "react-router-dom";
import searchResultContext from "./SearchResultContext";
const Search = () => {
const [wave,setWave] = useState("$perc");
const [pack_hu,setPackHu] = useState("$perc");
const { searchResult,setSearchResult } = useContext(searchResultContext);
useEffect(() => {
console.log(JSON.stringify(searchResult));
},[searchResult]);
//submit a form to search
const submitSearch = async (e) => {
e.preventDefault()
try {
const response = await fetch(
`http://localhost:5000/yourstage/search/${wave}/${pack_hu}`,{
method: "GET",headers: { "Content-Type": "application/json" },}
);
setSearchResult(await response.json());
//Reset Form and State
document.getElementById("searchForm").reset();
setWave("$perc");
setPackHu("$perc");
} catch (error) {
console.error(error.message);
}
};
//return the form html
return (
<Fragment>
<h1 className="text-center mt-3">Search</h1>
<form id="searchForm" onSubmit={submitSearch}>
<div className="form-group row">
<label htmlFor="Wave" className="col-sm-2 col-form-label">
Wave:
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control"
placeholder="Wave Number"
maxLength="10"
onChange={(e) => setWave(e.target.value)}
/>
</div>
</div>
<div className="form-group row">
<label htmlFor="pack_hu" className="col-sm-2 col-form-label">
Pack HU:
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control"
placeholder="Pack HU"
maxLength="10"
onChange={(e) => setPackHu(e.target.value)}
/>
</div>
</div>
<div className="row text-center mt-5">
{/**Search based on parameter*/}
<div className="col-6">
<button type="submit" className="btn-lg btn-primary">
<Link to="/yourstage/results">Search</Link>
</button>
</div>
</div>
</form>
</Fragment>
);
};
export default withRouter(Search);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。