reactjs - 我收到此错误“TypeError:无法解构'object null'的属性'handleShow',因为它为null。” 请帮我解决这个问题
问题描述
TypeError:无法解构'object null'的属性'handleShow',因为它是null。这个错误每次都会出现,但是当我刷新一切正常工作一段时间后,我尝试删除句柄显示并添加用obj替换它并在里面添加了obj&&obj.handleshow那么this.showModal函数不存在这个错误来了
Dashboard.js:
SearchModalRef = ({handleShow}) => {
this.showModal = handleShow;
}
onClick = () => {
this.showModal();
}
render(){
return(
<SearchModal ref={this.SearchModalRef} ></SearchModal>
<button type="button" onClick={this.onClick}>
Search
</button>
}
)
SearchModal.js:-
import React, { Component } from 'react';
import { SearchUser } from '../services/SearchService';
import Modal from 'react-bootstrap/Modal'
class SearchModal extends Component {
constructor(props){
super(props);
this.state = {
show: false,
search: '',
userdetails:[]
}
this.handleShow = this.handleShow.bind(this);
this.handleClose = this.handleClose.bind(this);
this.onTextboxChangeSearch = this.onTextboxChangeSearch.bind(this);
}
handleShow() {
this.setState({ show: true })
}
handleClose(){
this.setState({ show: false,search:'' })
}
onTextboxChangeSearch(event) {
const { value } = event.target;
this.setState({
search: value // <-- (1) update state
});
}
SearchForUser = async () => { // <-- (3) refactored search function
const { search, userdetails } = this.state;
const data = { username: search };
const user = await SearchUser(data);
this.setState({ userdetails: user.user });
}
componentDidUpdate(prevProps, prevState) {
if (prevState.search !== this.state.search) {
this.SearchForUser(); // <-- (2) search state updated, do search for user
}
}
render() {
let {search,userdetails}= this.state;
return (
<div>
<Modal show={this.state.show} onHide={this.handleClose}
dialogClassName="modal-90w"
aria-labelledby="example-custom-modal-styling-title"
>
<Modal.Header closeButton>
<Modal.Title>
<input
type="text"
placeholder="Search.."
value={search}
onChange={this.onTextboxChangeSearch}
></input>
</Modal.Title>
</Modal.Header>
<Modal.Body>
<h3>Users</h3>
<div>
<ul className="collection">
{userdetails.map((element,i) => {
return(
<li key={i}>{element.username}</li>
);
})}
</ul>
</div>
</Modal.Body>
</Modal>
</div>
)
}
}
export default SearchModal;
解决方案
以这种方式使用(更新)
SearchModalRef = (obj) => {
this.showModal = obj && obj.handleShow
}
推荐阅读
- sql - 按天获取代表的运行总和
- node.js - 我的护照-jwt设置哪里出错了?
- python - 查询最大值
- flutter - 使用同一个 Dio 实例触发多个请求时,拦截器锁不起作用
- sublimetext3 - 终点站自定义主题问题
- r - 为什么我的 ggplot 点对点而不是绘制一条回归线?
- python - 登录后未在 Django 中进行身份验证
- java - Firebase 自定义用户字段崩溃 - Android Studio
- google-bigquery - 删除同一数据库中的多个表 - 以相同的前缀开头 - Big Query
- xamarin - Xamarin / iOS / Crash on Launch / mono_handle_exception_internal / mini-exceptions.c,第 2782 行