【问题标题】:i cant redirect after getting a response using axios post request in react i tried using Redirect but not able to do it我在反应中使用 axios 发布请求获得响应后无法重定向我尝试使用重定向但无法做到
【发布时间】:2021-06-09 11:58:06
【问题描述】:

所以我尝试使用react-router-dom 组件重定向进行重定向,但我无法做到,我不明白为什么。请帮助我,我是初学者,无法清楚地理解代码发生了什么问题。

const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const res = await SearchAction(values);
    console.log(res.data);
    setResult(res.data); //this is the response

    <Redirect to={{ pathname: '/search/result', state: { data: `${res.data}` } }} />; //this is the  redirect
  } catch (err) {
    console.log('error searching', err);
  }
};

【问题讨论】:

    标签: reactjs redirect axios response react-router-dom


    【解决方案1】:

    问题:&lt;Redirect/&gt; 放置不当

    您的代码正在尝试在事件处理程序中呈现Redirect 组件。这没有意义,也不会奏效。事件处理程序可以修改您的状态,但它们不能直接呈现任何内容。

    解决方案:有条件地渲染&lt;Redirect/&gt;

    您应该根据组件的当前状态有条件地渲染RedirectRedirect 需要返回到正确的位置,即组件的 return 部分(或类组件的 render())。您只想在事件处理程序设置其数据后呈现Redirect。假设您的result 状态最初是undefined,我们可以检查result 的值,看看它是否已被数据更新。

    function MyComponent() {
      const [result, setResult] = useState();
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
          const res = await SearchAction(values);
          console.log(res.data);
          setResult(res.data); //this is the response
        } catch (err) {
          console.log("error searching", err);
        }
      };
    
      return (
        <div>
          {!!result && (
            <Redirect
              to={{ pathname: "/search/result", state: { data: result } }}
            />
          )}
    /* ... */
        </div>
      );
    }
    

    传递数据

    通过Redirect 传递大量数据并不是最好的主意。在我(非常有偏见的)看来,查询 API 应该是搜索结果页面的工作。最好将values 传递到您的"/search/result" 页面并将API 请求移到该组件中。

    【讨论】:

    • 非常感谢,这真的很有帮助。因为我不知道你不能把重定向放在一个函数中。
    猜你喜欢
    • 2021-06-08
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多