【问题标题】:Using react-router-dom with an input使用带有输入的 react-router-dom
【发布时间】:2021-08-03 04:50:54
【问题描述】:

我想重定向以使用 react-router-dom 重新呈现我在提交时写入输入的内容,但我不知道如何。

这是我的输入:

<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>

我有一个简单的列表,当我单击一个项目时,它会呈现我单击的口袋妖怪,这是可行的。但我希望在搜索时也能发生同样的情况。

我的搜索栏在我的列表上方,如下所示:

<SearchBar />
    <div className="container px-4 ">
        <Switch>
            <Route exact path="/">
                <PokemonList />
                <ViewMore />
            </Route>
            <Route exact path="/pokemon/:nameLink">
                <Pokemon />
            </Route>
        </Switch>
    </div>

我使用 useEffect 来获取特定数据:

useEffect(() => {
    dispatch(getPokemonData(nameLink));
}, [dispatch, nameLink]);

【问题讨论】:

    标签: javascript html reactjs redux react-router-dom


    【解决方案1】:

    没关系,我刚刚解决了。我做了什么:

    首次导入的useHistory:

    import { useHistory } from "react-router-dom";
    

    然后用它创建一个常量:

    const history = useHistory();
    

    然后push我要的url onSubmit:

    <form
        onSubmit={(e) => {
            e.preventDefault();
            dispatch(pokemonToSearch(value.toLowerCase()));
            history.push(`/pokemon/${value}`); // this right here
            setValue("");
        }}
    >
    </form>
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 2020-11-05
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2021-02-01
      • 2021-05-09
      相关资源
      最近更新 更多