ReactJS setState 变量是未定义的



我正在尝试过滤一个数组并使用该数组的过滤版本设置其状态。我的代码如下所示:

    class Overview extends Component {
      constructor() {
        super();
        this.state = {
          card: []
        }
      }
      deleteItem(id) {
        fetch('/api/v1/story/'+id,{
          method: 'DELETE',
        })
        .then(response => response.json())
        .then(response => {
          if(response['response'] == "success"){
            this.setState({
              //this is where it says this.state is undefined
              card: this.state.card.filter(s => s.storyId !== id)
            });
          }else{
            toastr.warning('dit item is al verwijderd', '', {positionClass: "toast-bottom-right", timeOut: 40000})
          }
        })
      }
      componentDidMount() {
        fetch('/api/v1/overview')
          .then((response) => response.json())
          .then((responseJson) => {
            this.setState({ 
              card: responseJson
            })
          })
      }
      render(){return (    
       <div className="deleteItem" onClick={deleteItem}>
       </div>
      )}

这里发生的事情是页面加载并填充卡片数组(有效(,然后卡片加载到 DOM 中,当您单击图标时,它应该从卡片数组中过滤掉已删除的卡片,然后将状态设置为过滤数组。

但是每当我到达this.setstate并尝试过滤它时,都会给我这个错误:

app.js:66418 未捕获(在承诺中(类型错误:无法读取未定义的属性"卡">

我希望我解释得足够好,并且有人可以帮助我解决这个问题。提前感谢!

试试这个。另外,为什么要制作 2 个 .then((?为什么不只使用一个并使用()=>{and here you can write more than one line}

已编辑:如果使用箭头函数,则无需绑定 THIS 的上下文https://medium.com/byte-sized-react/what-is-this-in-react-25c62c31480

如果不想使用箭头函数,则需要在构造函数中绑定上下文 this.myFunction= this.myFunction.bind(this);

class Overview extends Component {
      constructor() {
        super();
        this.state = {
          card: []
        }
      }
      deleteItem=(id)=> {
        fetch('/api/v1/story/'+id,{
          method: 'DELETE',
        })
        .then(response => response.json())
        .then(response => {
          if(response['response'] == "success"){
            this.setState({
              //this is where it says this.state is undefined
              card: this.state.card.filter(s => s.storyId !== id)
            });
          }else{
            toastr.warning('dit item is al verwijderd', '', {positionClass: "toast-bottom-right", timeOut: 40000})
          }
        })
      }
      componentDidMount() {
        fetch('/api/v1/overview')
          .then((response) => response.json())
          .then((responseJson) => {
            this.setState({ 
              card: responseJson
            })
          })
      }
      render(){return (    
       <div className="deleteItem" onClick={this.deleteItem}>
       </div>
      )}

最新更新