React中能否在componentDidMount方法中使用event事件对象?
问题原因
你在componentDidMount中调用handleSubmit时仅传入了查询关键词games,没有传入事件对象参数,导致函数执行e.preventDefault()时访问了undefined的属性抛出报错。另外在组件初始化挂载的场景下,本身不存在表单提交事件,也不需要执行阻止默认行为的逻辑。
解决方案
方案1:最小改动兼容调用场景
给event参数加可选校验,仅当事件对象存在时才执行阻止默认行为的逻辑:
handleSubmit = async (query, e) => { // 新增判断,仅e存在时执行阻止默认行为 e?.preventDefault(); // 原有API调用逻辑保持不变 };
修改后你componentDidMount中的调用逻辑不需要改动即可正常运行。
方案2:抽离公共逻辑(更推荐)
把搜索的业务逻辑和表单事件处理逻辑拆分,降低代码耦合度,后续维护更方便:
class App extends React.Component { constructor(props) { super(props); this.state = { inputValue: "", videos: [], selectedVideo: null, }; } componentDidMount() { // 初始化直接调用搜索方法 this.searchVideos("games"); } // 抽离公共的视频搜索方法 searchVideos = async (query) => { // 把你原有handleSubmit中的API调用逻辑放到此处 } handleSubmit = async (e) => { e.preventDefault(); // 表单提交时用当前输入值调用搜索方法 await this.searchVideos(this.state.inputValue); }; onInputChange = (e) => { const inputValue = e.target.value; this.setState({ inputValue }); }; render() { const inputValue = this.state.inputValue; return ( <div> <SearchBar handleSubmit={this.handleSubmit} inputValue={inputValue} onInputChange={this.onInputChange} /> </div> ); } }
额外注意
你的示例代码里有两处笔误,可同步修正避免其他问题:
- 输入事件方法名
onIputChange拼写错误,应为onInputChange - 组件名
SearhBar拼写错误,应为SearchBar
内容的提问来源于stack exchange,提问作者Talha Jutt
相关产品推荐
相关产品推荐

