【发布时间】:2021-12-29 08:43:12
【问题描述】:
我有一个功能,可以在用户单击注销按钮时检查用户数据以登录并删除缓存在这里上传我的代码,请帮助
反应代码:
import React, { useState, useEffect } from 'react';
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import axios from 'axios';
import Login from './new'
export function Logout (props) {
const { screen, setScreen } = props;
const deleteCookie = async () => {
try {
await axios.get('/clear-cookie');
setScreen('auth');
} catch (e) {
console.log(e);
}
};
return (
<div>
<button class="btn btn-secondary"onClick={deleteCookie} style={{marginTop:'10px'}}>Logout</button>
</div>
);
}
export function View (props) {
const { screen, setScreen } = props;
const [data, setData] = useState();
const deleteCookie = async () => {
try {
await axios.get('/clear-cookie');
setScreen('auth');
} catch (e) {
console.log(e);
}
};
const getData = async () => {
try {
const res = await axios.get('/home');
console.log(res.data)
setData(res.data);
} catch (e) {
console.log(e);
}
}
return (
<div className="App">
<p>{data}</p>
<Login />
{/* <button class="btn btn-secondary"onClick={deleteCookie} style={{marginTop:'10px'}}>Logout</button> */ }
</div>
);
}
function Apps() {
const [screen, setScreen] = useState('auth');
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const auth = async () => {
try {
const res = await axios.get('/authenticate', { auth: { username, password } });
if (res.data.screen !== undefined) {
setScreen(res.data.screen);
}
} catch (e) {
console.log(e);
}
};
const readCookie = async () => {
try {
const res = await axios.get('/read-cookie');
if (res.data.screen !== undefined) {
setScreen(res.data.screen);
}
} catch (e) {
setScreen('auth');
console.log(e);
}
};
useEffect(() => {
readCookie();
}, []);
return (
<div className="col-10" >
{screen === 'auth'
? <Form className="Login form " style={{paddingTop:'3%',paddingLeft:'25%',width:'80%', paddingRight:'25%'}} >
<Form.Group size="lg" controlId="email">
<Form.Label>Email</Form.Label>
<Form.Control
autoFocus
type="text"
onChange={(e) => setUsername(e.target.value)}
/>
</Form.Group>
<Form.Group size="lg" controlId="password">
<Form.Label>Password</Form.Label>
<Form.Control
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</Form.Group>
<Button block size="lg" type="submit" onClick={auth}>
Login
</Button>
</Form>
:<div> <View screen={screen} setScreen={setScreen} />
<Logout screen={screen} setScreen={setScreen} />
</div>
}
</div>
);
}
export default Apps;
我想导出“deleteCookie”功能,以便我可以使用那里的注销功能,请帮我解决这个问题
【问题讨论】:
-
提取redux调度函数中的逻辑
-
您可以使用
React.Context或传递deleteCookie函数。
标签: reactjs authentication react-functional-component