我正在使用react和next.js发出API请求(来自搜索栏),并在首页上显示电影列表,每个搜索结果会将我带到另一个页面,该页面将显示与该电影有关的数据。 每次刷新详细信息页面时,由于进行了错误的api请求,查询的结果都会丢失,并且当我使用向后/前进按钮时,搜索结果也会丢失。
index.js
<Link href={`/Details?id=${movie.imdbID}`}> //code to take me to the Details page
Details.js
const Details =()=>{
const router = useRouter();
let [result,setResult]=useState({});
const query=router.query.id; //storing the id from the URL
useEffect(() => {
axios.get('http://www.omdbapi.com/?',{params:{
apikey:'',i:query,plot:'full'
}
}).then(response=> setResult(response.data))
},[]);
return <SearchBar />
} export default Details;
我也已经在index.js中实现了一个Searchbar组件,该组件工作正常。我希望在details.js文件中使用相同的组件,以避免代码冗余,但是我不知道正确的方法。
index.js
<SearchBar whenSubmit={this.onSearchSubmit}/>
SearchBar.js
onFormSubmit=(event)=>{
event.preventDefault();
this.props.whenSubmit(this.state.term);
}
render(){
<form classname="ui form" onSubmit={this.onFormSubmit}>
<input type="text" value={this.state.term} placeholder="search any movie"
onChange={event=>this.setState({term: event.target.value})} />
</form>}