【问题标题】:How to link to certain page upon form submission using React Router如何在使用 React Router 提交表单时链接到特定页面
【发布时间】:2020-10-28 05:02:29
【问题描述】:

我正在学习 React Router,我有一个简单的导航栏组件,其中有一个输入/搜索栏。单击搜索时,它将搜索 API,我想使用 React Router 路由到新页面(/results)以显示结果。

我希望在单击提交按钮时显示我的组件SearchResults

这是我的代码:

const Search = () => {
  const apiKey = 'xxxxxx';
  const [input, setInput] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    searchAPI();
  };

  const searchAPI = async () => {
    const res = await fetch(`http://www.omdbapi.com/?apikey=${apiKey}&s=${input}`);
    const data = await res.json();
    console.log(data);
  };

  return (
    <form>
      <input onChange={(e) => setInput(e.target.value)}></input>
      <Link to="/results">
        <button type="submit" onClick={handleSubmit}>
          search
        </button>
      </Link>
    </form>
  );
};

这些是我的路线:

function App() {
  return (
    <>
      <Router>
        <Nav />
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/results" component={SearchResults} />
      </Router>
    </>
  );
}

我希望&lt;Link to="/results"&gt; 在提交时自动链接到 /results 页面,但事实并非如此。任何帮助将不胜感激!

【问题讨论】:

  • 我认为e.preventDefault() 阻止了链接,您尝试删除它吗?
  • 你还必须去掉 form 标记,无论如何这里似乎都不需要。

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


【解决方案1】:

看起来您正在使用支持钩子的 React 版本。在这种情况下,您可以利用 react-router 中的 useHistory 钩子,它允许您以编程方式更改路由。

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

const Search = () => {
  const apiKey = 'xxxxxx';
  const [input, setInput] = useState('');
  const history = useHistory();

  const handleSubmit = (e) => {
    e.preventDefault();
    searchAPI();
    history.push("/results");
  };

  const searchAPI = async () => {
    const res = await fetch(`http://www.omdbapi.com/?apikey=${apiKey}&s=${input}`);
    const data = await res.json();
    console.log(data);
  };

  return (
    <form>
      <input onChange={(e) => setInput(e.target.value)}></input>
      <button type="submit" onClick={handleSubmit}>
        search
      </button>
    </form>
  );
};

react router 中的Link 组件在概念上只是一个锚标记。在这种情况下,该解决方案可能有效,但您必须改变搜索的工作方式。您可以有一个指向/resultsLink 组件,然后您的SearchResults 组件可以根据用户输入执行搜索。为了使其工作,您必须将input 的值传递给Link,以便您以后可以访问它。 Here are some ways you can pass extra data in the Link component.

【讨论】:

  • @charlieyin 如果您包含 SearchResults 组件,我很高兴提供更多示例,说明如何从 URL 中提取查询参数并在搜索中使用这些参数。
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多