【发布时间】:2021-12-27 11:23:54
【问题描述】:
我有一个功能组件,我用反应控制用户登录。根据输入的用户名和密码,如果API返回的值为true,则重定向到另一个页面,如果为false,则停留在同一页面上。当我在用户名和密码正确的情况下按下按钮时,第一个值为它返回 undifined ,但当我第二次按下按钮时,它返回 true 并重定向到另一个页面。
console.log(isUser); // 当我检查时,即使名字和密码的值已满,它也显示未定义,但是当我再次按下按钮时,如果用户名和密码正确,则返回true。
这是什么原因?
export default function Login() {
const [isUser, setUser] = useState();
const [name, setName] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const history = useHistory();
let control;
function userControl() {
debugger;
let userService = new UserService();
userService.getUserControl(name, password).then((result) => setUser(result.data.data));
console.log(isUser);
if (isUser == true) {
history.push('/oee');
} else {
setUser(false);
setError('Kullanıcı Adınız veya Şifreniz Hatalı');
control = errorMessage();
}
}
function errorMessage() {
return (
<div>
<Message negative>
<Message.Header>{error}</Message.Header>
</Message>
</div>
);
}
return (
<div>
{control}
<Grid textAlign="center" style={{ height: '70vh' }} verticalAlign="middle">
<Grid.Column style={{ maxWidth: 450 }}>
<Header as="h2" color="teal" textAlign="center">
<Image style={{ height: 100, width: 200 }} src={ydclogo} />
</Header>
<Form size="large">
<Segment stacked>
<Form.Input
fluid
icon="user"
iconPosition="left"
placeholder="User Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<Form.Input
fluid
icon="lock"
iconPosition="left"
placeholder="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button color="teal" fluid size="large" onClick={userControl}>
Login
</Button>
</Segment>
</Form>
<Message>L3 RAPORLAMA SİSTEMİ</Message>
</Grid.Column>
</Grid>
</div>
);
}
【问题讨论】:
标签: javascript reactjs