代码之家  ›  专栏  ›  技术社区  ›  Ishan Patel

如何在不重新呈现组件的情况下更新反应状态?

  •  0
  • Ishan Patel  · 技术社区  · 6 年前

    我正在构建一个图库应用程序,需要在其中创建多个HTTP请求以提取图库条目(图像和视频)。

    因为Gallery将自动滚动条目,所以当我发出后续HTTP请求并更新状态时,我正在尝试阻止重新呈现组件。

    谢谢

    1 回复  |  直到 6 年前
        1
  •  5
  •   Colin Ricardo    6 年前

    下面是一个仅在满足特定条件(例如,完成提取)时重新渲染的示例。

    例如,这里我们只在值达到3时重新渲染。

    import React, { Component } from 'react';
    import { render } from 'react-dom';
    
    class App extends React.Component { 
      state = { 
        value: 0, 
      }
    
      add = () => {
        this.setState({ value: this.state.value + 1});
      } 
    
      shouldComponentUpdate(nextProps, nextState) { 
        if (nextState.value !== 3) { 
          return false;
        }
        return true;
      }
    
      render() { 
        return (
          <React.Fragment>
            <p>Value is: {this.state.value}</p>
            <button onClick={this.add}>add</button>
          </React.Fragment>
        )
      }
    }
    
    render(<App />, document.getElementById('root'));
    

    活生生的例子 here .