【问题标题】:Can I fetch api every time that props change on ComponentDidUpdate?每次在 ComponentDidUpdate 上更改道具时,我可以获取 api 吗?
【发布时间】:2020-05-16 13:04:36
【问题描述】:

正如你看到我的代码,我想从道具中获取 API contentUrl 的每一个变化。 但是浏览器会抛出这样的错误。有人帮助我吗?

警告:无法对未安装的组件执行 React 状态更新。 这是一个空操作,但它表明您的应用程序中存在内存泄漏。 要修复,取消所有订阅和异步任务 componentWillUnmount 方法。

【问题讨论】:

    标签: javascript reactjs web


    【解决方案1】:

    问题明确指出:无法执行 React 状态更新 未安装的组件

    所以在设置状态之前检查组件是否卸载_isMounted

    代码片段参考来自:HERE,希望这能解决你所有的疑惑

    class News extends Component {
      _isMounted = false;  // <----- HERE
    
      constructor(props) {
        super(props);
    
        this.state = {
          news: [],
        };
      }
    
      componentDidMount() {
        this._isMounted = true; // <----- HERE
    
        axios
          .get('YOUR_URL')
          .then(result => {
            if (this._isMounted) { // <----- CHECK HERE BEFORE SETTING UP STATE
              this.setState({
                news: result.data.hits,
              });
            }
          });
      }
    
      componentWillUnmount() {
        this._isMounted = false; // <----- HERE
      }
    
      render() {
        ...
      }
    }
    

    【讨论】:

      【解决方案2】:

      例如,如果调用完成并且您的组件已卸载,则会调用 setState。

      您可以通过以下条件来防止这种情况:

      _isMount = true;
      
      componentDidUpdate() {
        this.props.getContentJSON(url).then(() => {
          if(this._isMount){
            this.setState({...})
          }
        })
      }
      
      componentWillUnmount() {
        this._isMount = false;
      }
      
      

      或控制您的通话:

      controller = new AbortController();
      
      
      componentDidUpdate() {
        // I use fetch here but you can adapte to your code
        fetch(url, { signal: controller.signal }).then(() => {
            this.setState({...})
        })
      }
      
      componentWillUnmount() {
        controller.abort();
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-09
        • 2022-01-04
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多