【发布时间】:2020-03-04 06:41:46
【问题描述】:
我正在使用 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>}
【问题讨论】:
标签: javascript reactjs react-hooks next.js