React js:反应路由器不重定向

时间:2021-02-10 00:44:35

标签: reactjs redirect react-router

我是菜鸟学习反应,我不知道为什么这不能正常工作。 我想在按“Enter”时重定向到 /search,但由于某种原因它不起作用。 重定向到不同页面的正确方法是什么?

function App(){

    const [inputVal, setInputVal] = useState('');
    const [submitted, setSubmitted] = useState(false);

    function handleInput(e) {
        const query = e.target.value;
        setInputVal(query);
    }

    function handleKeyDown(e) {
        if (e.key === 'Enter') {
            setSubmitted(true);
            console.log(submitted);
            console.log(inputVal);
        }
    }

    return (
        <div className='App'>
            <div>
                <h1>Movie</h1>
                <input
                    onKeyDown={handleKeyDown}
                    onChange={handleInput}
                    placeholder='Search...'
                />
            </div>

            <Router>
                <Switch>
                    <Route path='/' exact component={Home} />
                    {submitted && <Redirect to='/search' />}
                    <Route path='/search' component={Search} />
                    <Route path='/details/:id' component={Detail} />
                </Switch>
            </Router>
        </div>
    );
}

2 个答案:

答案 0 :(得分:0)

我建议使用历史记录以编程方式导航到搜索。您可能希望将 inputVal 作为查询参数传递,以便您可以在该组件中访问它。

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

function App() {
    const history = useHistory();
    const [inputVal, setInputVal] = useState('');

    function handleInput(e) {
        const query = e.target.value;
        setInputVal(query);
    }

    function handleKeyDown(e) {
        if (e.key === 'Enter') {
            // You can put the inputVal as a query parameter
            history.push(`/search?search=${inputVal}`);
        }
    }

    return (
        <div className="App">
            <div>
                <h1>Movie</h1>
                <input
                    onKeyDown={handleKeyDown}
                    onChange={handleInput}
                    placeholder="Search..."
                />
            </div>

            <Router>
                <Switch>
                    <Route path="/" exact component={Home} />
                    <Route path="/search" component={Search} />
                    <Route path="/details/:id" component={Detail} />
                </Switch>
            </Router>
        </div>
    );
}

答案 1 :(得分:0)

它总是在你的 switch 中选择第一个,所以因为你在主页上,它可能永远不会看到下面的任何东西,这就是为什么它不会重定向你。您要么需要将重定向放在主路由上方,要么尝试使用 react-router 中的“历史记录”功能,这将要求您在根级别进行设置才能使用,但您可以这样做

function handleKeyDown(e) {
    if (e.key === 'Enter') {
        history.push('/search')
        console.log(submitted);
        console.log(inputVal);
    }
}
相关问题