当试图单击删除按钮时,会显示错误,指出无法读取null的props并尝试使用bind.this绑定构造函数类中的方法,但同样会显示相同的错误。还会将组件底部的值再次绑定到无法将props的值读取为null的相同错误
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import SampleData from './data.js';
import _ from 'lodash';
import AppList from './Applist';
import Appointment from './Appointment';
import './App.css';
class App extends Component {
constructor(){
super()
this.state = {
data:[],
aptBodyVisible: false
}
this.deleteMessage = this.deleteMessage.bind(this);
this.toggleAddDisplay = this.toggleAddDisplay.bind(this);
}
componentDidMount(){
this.setState({data: SampleData})
}
deleteMessage(item) {
var allApts = this.state.data;
var newApts = _.without(allApts, item);
this.setState({
data: newApts
});
}
toggleAddDisplay(){
var tempVisibility = !this.state.aptBodyVisible;
this.setState({
aptBodyVisible: tempVisibility
})
}
render() {
var filtered = this.state.data;
filtered = filtered.map((item, index)=>{
return(
<AppList key = { index }
singleItem = { item }
whichItem = { item }
onDelete = {this.deleteMessage}
/>
)
})
return (
<div className="main">
<Appointment
bodyVisible = { this.state.aptBodyVisible }
handleToggle = { this.toggleAddDisplay } />
<ul className="item-list media-list">{filtered} </ul>
</div>
);
}
}
export default App;
child class component
import React, { Component } from 'react';
class AppList extends Component {
handleDelete(){
this.props.onDelete(this.props.whichItem);
}
render(){
return(
<li className="pet-item media">
<div className="media-left">
<button className="pet-delete btn btn-xs btn-danger"
onClick = {this.handleDelete}>
<span className="glyphicon glyphicon-remove"></span></button>
</div>
<div className="pet-head">
<span className="pet-name">{this.props.singleItem.petName}</span>
<span className="apt-date pull-right">{this.props.singleItem.aptDate}</span>
</div>
<div className="owner-name"><span className="label-item">Owner:</span>
{this.props.singleItem.ownerName}</div>
<div className="apt-notes">{this.props.singleItem.aptNotes}</div>
</li>
)
}
}
export default AppList;
答案 0 :(得分:0)
在安装React组件之前,会调用它的构造函数。在为React.Component子类实现构造函数时,应该在任何其他语句之前调用super(props)。否则,this.props将在构造函数中未定义,这可能导致错误。
像这样:
constructor(props){
super(props);
this.state = {
data:[],
aptBodyVisible: false
}
this.deleteMessage = this.deleteMessage.bind(this);
this.toggleAddDisplay = this.toggleAddDisplay.bind(this);
}
答案 1 :(得分:0)
是的,我们需要绑定子组件中的方法,甚至可以使用click事件 onClick = {this.handleDelete.bind(this)}