[英]Using react-router-dom with an input
I want to redirect to use react-router-dom to re render what I write into my input when I submit, but I don't know how.我想重定向以使用 react-router-dom 重新呈现我在提交时写入输入的内容,但我不知道如何。
This is my input:这是我的输入:
<form
action="#"
onSubmit={(e) => {
e.preventDefault();
dispatch(pokemonToSearch(value.toLowerCase()));
setValue("");
}}
>
<div>
<input
value={value}
type="text"
onChange={(e) => setValue(e.target.value)}
/>
<button type="submit">Search</button>
</div>
</form>
I have a simple list, when I click one item, it renders the pokemon I clicked, that's works.我有一个简单的列表,当我单击一个项目时,它会呈现我单击的口袋妖怪,这是可行的。 But I want the same to happen when I search for one.
但是当我搜索一个时,我希望同样的事情发生。
My searchbar is above my list, like this:我的搜索栏在我的列表上方,如下所示:
<SearchBar />
<div className="container px-4 ">
<Switch>
<Route exact path="/">
<PokemonList />
<ViewMore />
</Route>
<Route exact path="/pokemon/:nameLink">
<Pokemon />
</Route>
</Switch>
</div>
I use a useEffect to fetch the specific data:我使用 useEffect 来获取特定数据:
useEffect(() => {
dispatch(getPokemonData(nameLink));
}, [dispatch, nameLink]);
Nevermind, I just solved it.没关系,我刚刚解决了。 What I did:
我做了什么:
First imported useHistory:首先导入 useHistory:
import { useHistory } from "react-router-dom";
Then created a constant with it:然后用它创建一个常量:
const history = useHistory();
Then push the url I want onSubmit:然后推送我要的url onSubmit:
<form
onSubmit={(e) => {
e.preventDefault();
dispatch(pokemonToSearch(value.toLowerCase()));
history.push(`/pokemon/${value}`); // this right here
setValue("");
}}
>
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.