代码之家  ›  专栏  ›  技术社区  ›  GregH

react?this3.deletearte不是函数

  •  1
  • GregH  · 技术社区  · 7 年前

    在回顾了其他一些类似的文章之后,我仍然不确定为什么会收到以下错误:

    TypeError: _this3.deleteArticle is not a function

    据我所知,问题是 deleteArticle 不包括在 state . 但是,我认为 .bind(this) 应将其绑定到 状态 以解决此问题。为什么这不起作用,我该怎么做才能纠正它?

    正在通过以下方式在呈现方法中调用 deleteartice function:。

    <td onClick={() => this.deleteArticle(article.Id).bind(this) }>
        <Glyphicon glyph='trash' />
    </td>
    

    如下所示:

      deleteArticle(id) {
        fetch('https://localhost:44360/api/articles/' + id, {  
            method: 'DELETE'
        }).then((response) => response.json())  
            .then((responseJson) => {  
                var deletedId = responseJson.id;
    
         var index = this.state.articles.findIndex(function(o){
            return o.id === deletedId;
         })  
          if (index !== -1){
            this.state.articles.splice(index, 1);
          } 
        })  
      }
    

    完整的组成部分是为了完整:

    import React, { Component } from 'react';
    import { Link } from 'react-router-dom';
    import { Glyphicon } from 'react-bootstrap';
    import { LinkContainer } from 'react-router-bootstrap';
    
    export class ArticlesIndex extends Component {
      displayName = ArticlesIndex.name
    
      constructor(props) {
        super(props);
        this.state = { articles: [], loading: true };
    
        fetch('https://localhost:44360/api/Articles/')
          .then(response => response.json())
          .then(data => {
            this.setState({ articles: data, loading: false });
          });
      }
    
      static renderArticlesTable(articles) {
        return (
          <table className='table'>
            <thead>
              <tr>
                <th>Id</th>
                <th>Title</th>
                <th>Description</th>
                <th>Edit</th>
                <th>Delete</th>
              </tr>
            </thead>
            <tbody>
              {articles.map(article =>
                <tr key={article.id}>
                  <td>{article.id}</td>
                  <td>{article.title}</td>
                  <td dangerouslySetInnerHTML={{ __html: article.description }}></td>
                  <td>
                    <LinkContainer to={'/articles/edit/' + article.id}>
                        <Glyphicon glyph='edit' />
                    </LinkContainer>
                </td>
                <td onClick={() => this.deleteArticle(article.Id).bind(this) }>
                  <Glyphicon glyph='trash' />
                </td>
                </tr>
              )}
            </tbody>
          </table>
        );
      }
    
      render() {
        let contents = this.state.loading
          ? <p><em>Loading...</em></p>
          : ArticlesIndex.renderArticlesTable(this.state.articles);
    
        return (
          <div>
            <h1>Articles</h1>
            {contents}
          </div>
        );
      }
    
      deleteArticle(id) {
        fetch('https://localhost:44360/api/articles/' + id, {  
            method: 'DELETE'
        }).then((response) => response.json())  
            .then((responseJson) => {  
                var deletedId = responseJson.id;
    
         var index = this.state.articles.findIndex(function(o){
            return o.id === deletedId;
         })  
          if (index !== -1){
            this.state.articles.splice(index, 1);
          } 
        })  
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Treycos    7 年前
    < P> static 方法未绑定到类的实例,并且将具有与典型组件不同的上下文。

    结果是类中的其他函数/变量将无法通过 this 关键字,因为它们的上下文不同。

    更改函数声明:

    static renderArticlesTable(articles)
    

    致:

    renderArticlesTable = articles => 
    

    可能会解决您的问题,因为我看不出您的函数是静态的。此外,使其成为箭头函数将自动将其绑定到类的上下文。

    您的电话:

     ArticlesIndex.renderArticlesTable(this.state.articles)
    

    现在将是:

    this.renderArticlesTable(this.state.articles)
    

    我也建议你换一下 deleteArticle 函数是不需要绑定的箭头函数:.

    deleteArticle = id => {
    

    另外,不要承诺触发 setState 在构造函数中。如果你 fetch 请求发送数据太早,您将设置未安装组件的状态。使用 componentDidMount 获取数据时:

    constructor(props) {
        super(props);
        this.state = { articles: [], loading: true };
    }
    
    componentDidMount(){
        fetch('https://localhost:44360/api/Articles/')
            .then(response => response.json())
            .then(data => {
                this.setState({ articles: data, loading: false });
            });
    }
    

    当我在这里时,您也可以将三元条件直接放入JSX中:

    render() {
        const { loading, articles } = this.state
    
        return (
            <div>
                <h1>Articles</h1>
                {loading ? 
                    <p><em>Loading...</em></p> 
                    : 
                    this.renderArticlesTable(articles)
                }
            </div>
        );
    }
    

    我还注意到,您正试图直接在 deleteparticle function中修改您的状态。如果不使用 setstate,则无法修改状态。

    要删除具有特定值的项,可以使用 filter 使用相应的 id 离开您以前的状态:

    deleteArticle = id => {
        fetch('https://localhost:44360/api/articles/' + id, {
            method: 'DELETE'
        }).then(response => response.json())
            .then(({ id }) => { //Deconstructs you responseJson
                this.sestState(prev => ({
                    articles: prev.articles.filter(article => article.id !== id)
                }))
            })
    }