Reactjs 未捕获类型错误:无法读取属性';昂迪斯米斯';未定义的
我有一篇文章:Reactjs 未捕获类型错误:无法读取属性';昂迪斯米斯';未定义的,reactjs,Reactjs,我有一篇文章: import React, { Component } from 'react'; const list = [ { title: 'React', url: 'https://facebook.github.io/react', author: 'Adam Beat', num_comments: 4, points: 3, objectID: 10, }, { title: 'Rails', url:
import React, { Component } from 'react';
const list = [
{
title: 'React',
url: 'https://facebook.github.io/react',
author: 'Adam Beat',
num_comments: 4,
points: 3,
objectID: 10,
}, {
title: 'Rails',
url: 'https://www.rubyonrails.org',
author: 'DHH',
num_comments: 8,
points: 4,
objectID: 11,
}
]
class Posts extends Component {
constructor(props) {
super(props); // call the constructor of the extended class
this.state = { // bound state with the this object
list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}
onDismiss(id) {
// const isNotId = item => item.objectID !== id;
// const updatedList = this.state.list.filter(isNotId);
const updatedList = this.state.list.filter(item => item.objectID !== id);
this.setState({ list: updatedList });
}
render() {
return (
<div className="home-page ui container">
{
this.state.list.map(function(item) {
return (
<ul key={item.objectID}>
<li>
<a href={item.url}>{item.title}</a>
</li>
<li>{item.author}</li>
<li>{item.num_comments}</li>
<li>{item.points}</li>
<li>
<button
onClick={ () => this.onDismiss(item.objectID)}
type="button">
Dismiss
</button>
</li>
</ul>
);
})
}
</div>
);
}
}
export default Posts;
import React,{Component}来自'React';
常数列表=[
{
标题:“反应”,
网址:'https://facebook.github.io/react',
作者:《亚当·巴特》,
num_评论:4,
要点:3,,
目标:10,
}, {
标题:“Rails”,
网址:'https://www.rubyonrails.org',
作者:'DHH',
num_评论:8,
要点:4,
目标:11,
}
]
类Posts扩展组件{
建造师(道具){
super(props);//调用扩展类的构造函数
this.state={//和该对象绑定的状态
列表:列表,
};
this.onDismiss=this.onDismiss.bind(this);
}
昂迪斯米斯(id){
//const isNotId=item=>item.objectID!==id;
//const updatedList=this.state.list.filter(isNotId);
const updatedList=this.state.list.filter(item=>item.objectID!==id);
this.setState({list:updatedList});
}
render(){
返回(
{
this.state.list.map(函数(项){
返回(
-
- {item.author}
- {item.num_comments}
- {item.points}
-
this.onDismiss(item.objectID)}
type=“button”>
解雇
);
})
}
);
}
}
导出默认职位;
我试图通过点击“取消”按钮从列表中删除一个项目
但实际上我得到了一个错误:“UncaughtTypeError:无法读取未定义的'onDismiss'属性”
我缺少什么?您使用的是
this.state.list.map(函数(项){…})
,因此您的上下文是map
函数的上下文。如果将其更改为this.state.list.map(item=>{…})
它将工作。这是因为arrow函数会自动绑定到父级This
范围。在map
函数中没有onDismiss
函数
在构造函数中绑定此时,
onDismiss
函数将接收组件上下文。但是,您仍然必须传递components函数,在这种情况下,您不需要这样做。构造函数中不需要属性初始值设定项语法,因为您已经在使用执行绑定的arrow函数回调。