gpt4 book ai didi

javascript - 重新路由后组件不呈现

转载 作者:行者123 更新时间:2023-12-04 07:41:20 26 4
gpt4 key购买 nike

我有一个问题,当我输入有效的电子邮件并将日志状态设置为 true 时,组件会重定向,但不会呈现。我的应用程序包含在 BrowserRouter 中。地址栏显示正确的路径,但没有呈现任何内容。

function App() {
const [savedEmail, setSavedEmail] = useState(localStorage.getItem("email"));
const [loggedIn, setLoggedIn] = useState(localStorage.getItem("logged"));
return (
<>
<PropContext.Provider value={{ loggedIn, setLoggedIn, setSavedEmail }}>
<Header />
<Switch>
<Route
exact
path="/"
render={() => {
return loggedIn ? (
<Redirect to="/users" />
) : (
<Redirect to="/login" />
);
}}
></Route>
{loggedIn ? (
<Redirect to="/users" />
) : (
<Route exact path="/login" component={Login} />
)}

{loggedIn ? (
<Route exact path="/users" component={Users} />
) : (
<Redirect to="/login" />
)}
</Switch>
</PropContext.Provider>
</>
);
}
这是处理状态更新的登录页面,它应该更新应用程序的状态并重定向到/users,它会这样做,但不会呈现它。
function Login() {
const [email, setEmail] = useState("");
const [validEmail, setValidEmail] = useState(false);
const { loggedIn, setLoggedIn, setSavedEmail } = useContext(PropContext);

const handleClick = () => {
if (!localStorage.getItem("email")) {
setSavedEmail(email);
localStorage.setItem("email", email);
setLoggedIn(true);
localStorage.setItem("logged", true);
console.log("if");
} else if (localStorage.getItem("email") === email) {
setLoggedIn(true);
localStorage.setItem("logged", true);
console.log("else if");
}
};

const emailIsValid = () =>
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
email
);

useEffect(() => {
emailIsValid(email) ? setValidEmail(true) : setValidEmail(false);
}, [email]);
return (
<div>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
type="email"
name="email"
id="email"
required
/>
<button disabled={!validEmail} onClick={() => handleClick()}>
Log in
</button>
</div>
);
}

最佳答案

这里的问题是您的“路线”似乎没有被重新评估。将每个路由/重定向包装在呈现的 Route 中.

<Switch>
<Route
path="/login"
render={() =>
loggedIn ? (
<Redirect to="/users" />
) : (
<Route exact path="/login" component={Login} />
)
}
/>
<Route
path="/users"
render={() =>
loggedIn ? (
<Route exact path="/users" component={Users} />
) : (
<Redirect to="/login" />
)
}
/>
<Redirect from="/" to={loggedIn ? "/users" : "/login"} />
</Switch>
Edit component-doesnt-render-after-rerouting

关于javascript - 重新路由后组件不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67444840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com