我正在尝试制作一个搜索表单组件,该组件在提交时会将输入值传递给该组件。问题是当搜索到的组件被重定向的组件重用时,我收到了未定义的错误。
这是搜索表单组件
import React,{useState,useEffect} from 'react'
import { useHistory } from 'react-router';
const SearchForm = ()=>{
const [text,setText] = useState('');
const history = useHistory();
const handleChange = (e)=>{
setText(e.target.value)
}
const handleSubmit = (e)=>{
history.push({
pathname: '/search',
state: {
search: text
}
})
setText('');
}
return (
<div className="searchForm">
<form onSubmit = {handleSubmit}>
<input type="text" onChange = {handleChange} value = {text}/>
<button type = "submit" className = "banner banner-button btn-sm">Search</button>
</form>
</div>
)
}
export default SearchForm
Here is the Component to which renders on submitting the form and passing the searched value
import React, { useState,useEffect } from 'react'
import { useLocation } from 'react-router'
import Navbar from '../../Navbar/Navbar'
import SearchForm from '../../SearchForm/SearchForm'
import Loading from '../../Loading/Loading'
import SearchResult from './SearchResult'
import './search.css'
const Search = () => {
const [loading,setLoading] = useState(false);
const [movies,setMovies] = useState([]);
const location =useLocation();
const searchedTerm = location.state;
useEffect(()=>{
setLoading(true);
const get = async(term)=>{
const res = await fetch(`/${term}`)
const data = await res.json();
return data;
}
get(searchedTerm.search)
.then((response)=>{
setMovies(response.data.movies)
setLoading(false);
})
.catch((err)=> console.log(err));
},[])
return (
<div className = 'searched-video'>
<Navbar/>
{/* <SearchForm /> */}
{loading ? <Loading/> :
<div className="searched-content">
{
movies.map((element,index)=>{
return (<SearchResult key = {index} title = {element.title_english} runtime = {element.runtime} genres = {element.genres[0]} summary = {element.summary} img = {element.medium_cover_image} hash = {element.torrents[0].hash} quality = {element.torrents[0].quality} />)
})
}
</div>
}
</div>
)
}
export default Search
如果有人帮助解决这个问题,那将非常有帮助。谢谢!
答案 0 :(得分:0)
提交处理程序不会阻止提交表单时的默认表单操作,页面和应用程序正在重新加载并且您会丢失转换的路由状态。
防止默认表单操作。您可能也不需要清除 text
状态,因为无论如何路由转换都可能卸载此组件。
const handleSubmit = (e) => {
e.preventDefault(); // <-- prevent form submission reloading page
history.push({
pathname: '/search',
state: {
search: text
}
});
}