如何在React js中搜索时重定向到另一个页面



我目前被应用程序的一部分卡住了,如果你点击handleSubmit,目标是将你带到产品结果页面。我的逻辑是,我认为我在return语句中把它放错了地方。如果有人能发现这个问题,那就太棒了!提前感谢您!

const Search = () => {
const [productName, setProductName] = useState('')
const [result, setResult] = useState([])
const handleSubmit = (event) => {
event.preventDefault()
axios
.get(`https://topical.herokuapp.com/api/search?name=${productName}`, {
name: productName
}).then(result => setResult(result))
}
return (
<div>
<form onSubmit={handleSubmit.then(<Redirect to={`/productlist/${productName}`} />)}>
<TextField
label='Enter Product Name:' value={productName}
onChange={event => setProductName(event.target.value)}
InputProps={{
endAdornment: (
<InputAdornment>
<IconButton type='submit'>
<SearchIcon />
</IconButton>
</InputAdornment>
)
}}
/>
</form>

您的函数handleSubmit不是Promise。

因此,它没有.then语句。

您应该做的是将handleSubmit更改为async函数,然后try-catch finally该方法。之后,等待axios,因为这是一个承诺。

当结果不为空时,进行重定向。

这是我最喜欢的异步组件级函数处理程序模式。

const handleSubmit = async (event) => {
try {
// can put loading of some kind like setLoading(true);
event.preventDefault();
const result = await axios
.get(`https://topical.herokuapp.com/api/search?name=${productName}`, {
name: productName
});
if(!result) {
return;
// can throw custom exception here like throw new Error("Searching failed.");
}
setResult(result);
history.push(`/productlist/${productName}`);
} catch (ex) {
console.error(ex.message);
} finally {
// stop the loader if any setLoading(false);
}
}

不确定您是如何管理路由的,但为了让代码正常工作,您可以更改返回方法,因此,当您得到结果时,页面将重定向您的组件。

const Search = () => {
const [productName, setProductName] = useState('')
const [result, setResult] = useState(null)
const handleSubmit = (event) => {
event.preventDefault()
axios
.get(`https://topical.herokuapp.com/api/search?name=${productName}`, {
name: productName
}).then(result => setResult(result))
}
if (result){
return <Redirect to={`/productlist/${productName}`} />
}
return (
<div>
<form onSubmit={handleSubmi}>
<TextField
label='Enter Product Name:' value={productName}
onChange={event => setProductName(event.target.value)}
InputProps={{
endAdornment: (
<InputAdornment>
<IconButton type='submit'>
<SearchIcon />
</IconButton>
</InputAdornment>
)
}}
/>
</form>

正确的方法是使用React Navigation——Hello Example应该以更好的方式解决您的问题。

最新更新