[英]Why calling set function of useState hook applies immediately in async functions?
[英]Why is state set to null immediately after setter function defined by useState is called?
我將我的 App.js 重構為一個功能組件。 當我嘗試登錄時,我的 currentUser 設置為用戶,但隨后立即設置為 null。 我很困惑為什么在給定值后將 currentUser 設置為 null 。 是否再次調用setCurrentUser
將其設置為 null?
應用程序.js:
const App = (props) => {
const [ currentUser, setCurrentUser ] = useState(null)
const [ shoppingCart, setShoppingCart ] = useState([])
const handleLogin = (email, password, history) => {
axios({
method: 'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: { email, password},
url: 'http://localhost:3000/api/v1/login'
})
.then( res => setCurrentUser(res.data.user))
}
console.log('this is currentUser', currentUser)
return (
<Switch>
<div>
<SideDrawer currentUser={currentUser} setCurrentUser={setCurrentUser}/>
<div className='App'>
{/** OTHER ROUTES HERE **/}
<Route path='/login' render={
() => {
return (
<Login handleLogin={handleLogin} history={props.history} currentUser={currentUser}/>
)
}
} />
{/* Route to Signup page */}
<Route path='/signup' render={
() => {
return(
<SignupForm setCurrentUser={setCurrentUser} history={props.history}/>
)
}
} />
</div>
</div>
</Switch>
登錄.js
const Login = ({history, handleLogin}) => {
const classes = useStyles()
const [ values, setValues ] = useState({
email: '',
password: '',
showPassword: false
})
const handleChange = e => {
const { name, value } = e.target
setValues({ ...values, [name]: value})
}
const handleShowPassword = () => {
setValues({...values, showPassword: !values.showPassword})
}
const handleMouseDownPassword = (e) => {
e.preventDefault()
}
return (
<Box className={classes.container}>
<h1>Login</h1>
<FormGroup>
<FormControl variant="outlined">
<TextField
className={classes.text}
variant='outlined'
multiline
name='email'
label="Email"
onChange={handleChange}
/>
</FormControl>
<FormControl variant='outlined'>
<TextField
label='Password'
className={classes.text}
type={values.showPassword ? 'text' : 'password'}
name='password'
margin="normal"
variant='outlined'
onChange={handleChange}
InputProps={{
endAdornment: (
<InputAdornment>
<IconButton
onClick={handleShowPassword}
onMouseDown={handleMouseDownPassword}
>
{values.showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
)
}}
/>
</FormControl>
<Button
variant='contained'
className={classes.button}
onClick={ () => handleLogin(values.email, values.password, history)}
>
Login
</Button>
</FormGroup>
</Box>
)
}
有些東西將其設置為 null。
要么: .then( res => setCurrentUser(res.data.user))
或SideDrawer
或SignupForm
正在調用setCurrentUser(null)
。
如果您同時刪除SideDrawer
和SignupForm
,您可以檢查 .then .then( res => setCurrentUser(res.data.user))
行的功能。
然后添加回SideDrawer
並查看是否導致它被設置為 null。 最后,添加回SignupForm
並查看是否是罪魁禍首。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.