[英]Why location.state is null when using react router v6 link to pass props?
[英]React Router Redirect if location.state is null
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
将useState
移动到 function 的顶部(在 if 条件之上)或将 if 条件移动到useEffect
并从那里重定向。
function Update(data) {
const [name, setName] = useState(data.location.state.name);
if(!data.location.state) {
return <Redirect to="/"/>
}
return (<>Hello World</>)
}
(类似的堆栈溢出问题,可能包含有用的答案。)
从文档:
不要在循环、条件或嵌套函数中调用 Hook。 相反,在任何提前返回之前,始终在 React function 的顶层使用 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</>
);
}
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
function Update(data) {
const [name, setName] = useState(
data.location.state ? data.location.state.name : ''
);
if(!data.location.state) return <Navigate replace to="/"/>
return (
<>Hello World</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.