【问题标题】:API request in ReactReact 中的 API 请求
【发布时间】:2018-12-17 10:58:54
【问题描述】:

我正在尝试构建一个带有反应的 .net 核心网络应用程序。但是,我正在为一些 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 工作正常,但是当我单击 DELETE 按钮时,它说:_this.deleteHandle is not a function。

请帮忙,非常感谢。

【问题讨论】:

    标签: .net reactjs api asp.net-core


    【解决方案1】:

    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)}/>
    ));
    

    【讨论】:

      【解决方案2】:

      您需要将删除事件传递给每个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;
      

      【讨论】:

        【解决方案3】:

        您的问题是您直接调用 deleteHandle,而不是传递调用它的函数。使用箭头函数,解决方案非常简单:

        <a onClick={()=> this.deleteHandle(doc.id)}>Delete</a>
        

        【讨论】:

          猜你喜欢
          • 2021-07-03
          • 1970-01-01
          • 2020-06-10
          • 2021-05-31
          • 2021-12-29
          • 2018-12-09
          • 2022-12-03
          • 1970-01-01
          • 2018-12-09
          相关资源
          最近更新 更多