我正在尝试使用 React 构建一个 .net core Web 应用程序。然而,我在一些 API 调用和功能上遇到了困难。以前可能有人问过这个问题,但我自己找不到解决方案。
class Documents extends Component{
constructor(props){
super(props);
this.state = {
docs: []
};
this.deleteHandle = this.deleteHandle.bind(this);
}
componentDidMount(){
const url = 'api/Documents';
fetch(url)
.then((response) => {
return response.json();
})
.then((data) =>{
this.setState({
docs: data
});
})
.catch((error) => console.log(error));
}
renderDocuments(){
return this.state.docs.map((doc) => (
<Doc key={doc.id} doc = {doc}/>
));
}
deleteHandle(id) {
fetch('api/Documents/'+id, { method: 'DELETE' })
.then((response) => {
return response.json();
})
.catch((error) => console(error));
}
render(){
return (
<ul>
{this.renderDocuments()}
</ul>
);
}export default Documents;
这是我的 Doc.js
const Doc = ({ doc }) => (
<li>
<p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
<a onClick={this.deleteHandle(doc.id)}>Delete</a>
</li>);export default Doc;
API 和 Get 工作正常,但是当我单击“删除”按钮时,它显示:
_this.deleteHandle 不是函数。
请帮忙。
Doc
没有称为 deleteHandle
的属性。只有Documents
有。您需要将处理程序传递给 Doc
:
const Doc = ({ doc, onDelete }) => (
<li>
<p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
<a onClick={onDelete}>Delete</a>
</li>);
export default Doc;
在
Documents.renderDocuments
:
return this.state.docs.map((doc) => (
<Doc key={doc.id} doc = {doc} onDelete={() => this.deleteHandle(doc.id)}/>
));
您需要将删除事件传递给每个
Doc
,以便可以使用它:
renderDocuments(){
return this.state.docs.map((doc) => (
<Doc key={doc.id} doc = {doc} onDelete={(id) => this.deleteHandle(id)} />
));
}
然后在
Doc
:
const Doc = ({ doc, onDelete }) => (
<li>
<p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
<a onClick={onDelete(doc.id)}>Delete</a>
</li>);
export default Doc;
您的问题是您直接调用deleteHandle,而不是传递调用它的函数。使用箭头函数,解决方案非常简单:
<a onClick={()=> this.deleteHandle(doc.id)}>Delete</a>