ReactJS setState变量未定义

时间:2019-06-11 12:35:37

标签: javascript reactjs

我试图过滤一个数组,并使用该数组的过滤版本设置其状态。我的代码如下:

    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未捕获(承诺)TypeError:无法读取未定义的属性“ card”

我希望我解释得足够好,并且有人可以帮助我。预先感谢!

1 个答案:

答案 0 :(得分:2)

尝试一下。 另外,为什么还要创建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>
      )}