【问题标题】:React Router Redirect if location.state is null如果 location.state 为空,则反应路由器重定向
【发布时间】:2021-08-29 03:49:55
【问题描述】:
    import React, { useState } from "react";
    import { Redirect } from "react-router-dom";
    
    function Update(data) {
       if(!data.location.state) return <Redirect to="/"/>
       const [name, setName] = useState(data.location.state.name);
       return (<>Hello World</>)
}

错误:有条件地调用 React Hook “useState”。 React Hooks 必须在每个组件渲染中以完全相同的顺序调用 react-hooks/rules-of-hooks

【问题讨论】:

标签: javascript reactjs typescript react-router-dom


【解决方案1】:

useState 移动到函数顶部(在 if 条件上方)或将 if 条件移动到 useEffect 内并从那里重定向。

function Update(data) {
 const [name, setName] = useState(data.location.state.name);
     
 if(!data.location.state) {
      return <Redirect to="/"/>
 }

  return (<>Hello World</>)
}

【讨论】:

  • 这是完全错误的。 useState(data.location.state.name) 会抛出错误,因为它是未定义的。这就是我在顶部检查并尝试重定向的原因。
  • 您可以使用data?.location?.state?.name ?? ""避免该错误
【解决方案2】:

(类似的Stack Overflow question 可能包含有用的答案。)

From the docs:

不要在循环、条件或嵌套函数中调用 Hooks。相反,总是在你的 React 函数的顶层使用 Hooks,在任何提前返回之前

所以useState 钩子调用应该移动到组件的顶部

你可以这样做:

import React, { useState } from "react";
import { Redirect } from "react-router-dom";
    
function Update(data) { 
  const [name, setName] = useState(
    data.location.state ? data.location.state.name : ''
  );

  if(!data.location.state) return <Redirect to="/"/>

  return (
    <>Hello World</>
  );
}

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2020-10-22
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多