问题描述
我创建了一个表单,该表单在按下“提交”按钮后调用搜索功能。我希望搜索结果显示在另一个功能组件中(为此目的使用了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 (将#修改为@)