React页面渲染为空白,本应显示输入框列表却无法正常工作如何解决?
问题排查与修复方案
首先你可以打开浏览器F12控制台,就能看到明确的运行时报错,这些报错直接阻断了组件渲染。以下是所有需要修复的问题:
错误列表
- 重复导出冲突:同一文件中先后两次声明
export default,会直接导致模块加载失败,组件无法被正常引入渲染。 - 组件命名违规:React自定义组件必须使用大驼峰命名,你定义的
user_update_info为小写开头,会被React识别为原生HTML标签,不会执行组件内的渲染逻辑。 - 事件绑定与拼写错误:
onSubmit方法没有在构造函数中绑定this,执行时会出现this指向异常- form标签的提交事件错误写为大写开头的
OnSubmit,React事件要求小驼峰写法onSubmit,同时绑定的方法名错误写为大写开头的this.OnSubmit,和实际定义的方法不匹配 e.PreventDefault()的preventDefault首字母应为小写,大写会抛出方法不存在的错误
- 数据读取与语法错误:
- 构造user对象时使用
=赋值,对象键值对需要使用:分隔 - 密码输入框的value绑定了不存在的
this.state.Passworde(末尾多了e),state中仅定义了Password,读取不存在的属性会引发运行时报错
- 构造user对象时使用
- 冗余导入:未使用的
useState、Link、axios、useHistory可直接删除,不会影响功能。
修正后的完整代码
import React, { Component } from "react"; export default class UserUpdateInfo extends Component{ constructor(props){ super(props); this.onChangeEmail = this.onChangeEmail.bind(this); this.onChangePassword = this.onChangePassword.bind(this); this.onChangeName = this.onChangeName.bind(this); this.onChangeType = this.onChangeType.bind(this); this.onSubmit = this.onSubmit.bind(this); this.state = { Name:'', Email:'', Password:'', Type:'' } } onChangeName(e) { this.setState({ Name: e.target.value }); } onChangeEmail(e) { this.setState({ Email: e.target.value }); } onChangePassword(e) { this.setState({ Password: e.target.value }); } onChangeType(e) { this.setState({ Type: e.target.value }); } onSubmit(e){ e.preventDefault(); const user = { Name: this.state.Name, Email: this.state.Email, Password: this.state.Password, Type: this.state.Type } console.log(user) window.location = '/SignIn'; } render(){ return( <div> <h3>You are updating your info</h3> <form onSubmit = {this.onSubmit}> <div className = "form-group"> <label>Name:</label> <input type = "text" required className="form-control" value={this.state.Name} onChange={this.onChangeName}/> </div> <div className = "form-group"> <label>Email:</label> <input type = "text" required className="form-control" value={this.state.Email} onChange={this.onChangeEmail}/> </div> <div className = "form-group"> <label>Password:</label> <input type = "password" required className="form-control" value={this.state.Password} onChange={this.onChangePassword}/> </div> <div className = "form-group"> <label>Type:</label> <input type = "text" required className="form-control" value={this.state.Type} onChange={this.onChangeType}/> </div> <div className="form-group"> <button type="submit" className="btn btn-primary">提交修改</button> </div> </form> </div> ) } }
注:额外修正了密码输入框的type为password避免明文显示,补充了提交按钮保证表单可正常提交。
内容的提问来源于stack exchange,提问作者aaaEEE14
相关产品推荐
相关产品推荐

