为什么在调用 useState 定义的 setter 函数后立即将状态设置为 null?



我将我的应用程序.js重构为功能组件。当我尝试登录时,我的当前用户设置为用户,但随后立即设置为 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))

SideDrawerSignupForm正在呼叫setCurrentUser(null).

如果同时删除SideDrawerSignupForm则可以检查.then( res => setCurrentUser(res.data.user))行的功能。

然后添加回SideDrawer,看看这是否导致它设置为 null。最后,重新添加SignupForm,看看这是否是罪魁祸首。

最新更新