React两步注册表单提交后props未更新,如何传值到第二步组件?
问题根因
你当前的两步注册数据无法同步,核心原因是表单数据只存储在RegisterMain组件的内部state中,没有同步到路由层RegisterOrg维护的公共formState里,所以第二步组件拿到的永远是初始值。具体问题点如下:
Register组件传参命名不规范:给RegisterMain传递表单初始值时,prop名错误设为了props,后续取值逻辑易混淆RegisterMain未同步状态到上层:输入框触发的onChange仅更新自身内部state,没有调用上层传入的onChange方法同步数据到公共formState- 提交逻辑缺失状态同步和路由跳转:表单提交后没有确认同步最新表单数据到公共状态,也没有跳转到第二步路由
修复步骤
1. 修正Register组件传参
class Register extends Component { render() { return ( <div className=""> <div className="row register-row-edit"> <div className={"col-lg-6 col-12"}> <RegisterGif/> </div> <div className={"col-lg-6 col-12 mt-5"}> {/* 把prop名从props改为values,语义更清晰 */} <RegisterMain values={this.props.values} onChange={this.props.handleChange}/> </div> </div> </div> ); } } export default Register;
2. 改造RegisterMain组件
首先从react-router-dom引入withRouter高阶组件,用于跳转路由,然后修改组件逻辑:
import { withRouter } from 'react-router-dom' class RegisterMain extends Component { constructor(props) { super(props); this.onSubmit = this.onSubmit.bind(this) this.onChange = this.onChange.bind(this) // 初始化state使用上层传入的values,支持回显 this.state = { ...props.values } } static propTypes = { isAuthenticated: PropTypes.bool, register: PropTypes.func.isRequired, } onSubmit = (e) => { e.preventDefault(); const newUser = {...this.state}; this.props.register(newUser); // 提交时再同步一次最新数据到公共状态,确保数据一致 this.props.onChange(newUser); // 跳转到第二步注册页,替换为你实际的注册路由前缀即可 this.props.history.push('/register/step-two'); console.log(newUser) } onChange(event) { const value = event.target.value; const newState = { ...this.state, [event.target.name]: value } this.setState(newState) // 输入变更时同步最新表单数据到上层公共状态 this.props.onChange(newState) } // render方法保持原有逻辑不变,此处省略 } const mapStateToProps = (state) => ({ isAuthenticated: state.isAuthenticated, error: state.error, user : state.auth, }) // 导出时用withRouter包裹,获取路由跳转能力 export default connect(mapStateToProps, {register})(withRouter(RegisterMain));
修改完成后,RegisterOrg维护的公共formState就会跟随表单输入实时更新,提交后跳转至第二步也能拿到最新的表单数据。
内容的提问来源于stack exchange,提问作者Sajjad Shiasi
相关产品推荐
相关产品推荐

