无法在已卸载的组件上调用setState(或forceUpdate)。这是一项禁止操作,但有人知道您的应用程序中存在内存泄漏吗?

时间:2018-08-07 02:08:54

标签: javascript node.js reactjs react-native vue.js

我想在页面中显示列表,但是我仍然混淆使用componentDidMount和componentWillMount,但是我得到了这个错误: 无法在已卸载的组件上调用setState(或forceUpdate)。这是空操作,但它表明应用程序中发生内存泄漏。要解决此问题,请在componentWillUnmount方法中取消所有订阅和异步任务。     在文章中(由LatestNews创建)     在div中(由LatestNews创建)     在div中(由LatestNews创建)

import React from 'react';
import api from '../../api/article';

class Articles extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      articles: [],
      isMounted: false
    }
  }

  componentDidMount() {
     this.timer = setInterval(() =>  this.setState({ isMounted: true }, () => {
        if (this.state.isMounted) {
          this.setState({ isMounted: false });
          {
            // do something
            // this.props.onClick(...)
          }
        }
      }), 5000);
    }
  

  componentWillMount() {
    clearInterval(this.timer)
    api.getArticles()
      .then( articles => {
        console.log(articles)
        this.setState({articles:articles.article})
      })
      .catch(err => console.log(err))
  }

  render() {
    console.log('render disini')
    return (
      
      <div className="blogpost">
       {this.state.articles.map((news, i) => {
        return (
          <React.Fragment>
          <div className="image-wrapper">
            <img className="responsive-img" src="http://loremflickr.com/320/240" />
          </div>
          <div className="content"  key={i}>
            <h4>{news.tittle}</h4>
            <p>{news.content}</p>
          </div>
          <div className="footer">
            <div className="row">
              <div className="footer-content">
                <i className="material-icons">today</i>
                <span>{this.formatDate(news.created)}</span>
              </div>
              <div className="footer-content">
                <i className="material-icons">chat bubble outline</i>
                <a href="">6</a>
              </div>
            </div>
          </div>
          <div className="read-more">
            <a href="">Read more</a>
          </div>
          </React.Fragment>
            );
          })};
      </div>
    );
  };
}
export default Articles;

0 个答案:

没有答案