【发布时间】:2021-02-19 00:56:45
【问题描述】:
我有一些代码从我的数据库中返回,我想在 .then 中重定向 - 何时以及是否有 res ,但是当我将 history.push 放入 .then 时 - 它不会呈现任何在.then里面 这是一些代码:
import React, { useState } from 'react'
import { connect } from "react-redux";
import { CreateAccount as createAccountService } from '../services/user'
import { actions } from '../store/actions';
import { Redirect, withRouter } from "react-router-dom";
import { useHistory } from 'react-router-dom';
const mapStateToProps = (state) => {
return { ...state, user: state.userReducer.user || [] }
}
const mapDispatchToProps = (dispatch) => ({
setUser: (loggedUser) => dispatch(actions.setUser(loggedUser))
})
const CreateAccount = withRouter(function CreateAccount(props) {
const history = useHistory();
const [nameI, setName] = useState('');
const [emailI, setEmail] = useState('');
const [passwordI, setPassword] = useState('');
function createAccountHandler() {
createAccountService({ name: nameI, email: emailI, password: passwordI })
.then(res => {
alert(res.name) //brings the res.name but when the history.push is here it doens't show the alert
history.push('/posts') // <= the problem!
})
.catch((err) => {
alert('err in createAccount' + err)
})
}
return (<>
<div className="wrapper fadeInDown">
<div id="formContent">
<form>
<input type="text" id="name" class="fadeIn first" name="name" placeholder="name" onChange={e => setName(e.target.value)} />
<input type="text" id="email" class="fadeIn second" name="email" placeholder="email" onChange={e => setEmail(e.target.value)} />
<input type="text" id="password" class="fadeIn third" name="createAccount" placeholder="password" onChange={e => setPassword(e.target.value)} />
<input onClick={createAccountHandler} type="submit" class="fadeIn fourth" value="Create Account" />
</form>
</div>
</div>
</>)
}
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(CreateAccount);
【问题讨论】: