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

新手上路,请多包涵

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

由于画廊将自动滚动条目,因此我试图在发出后续 HTTP 请求并更新状态时防止重新呈现组件。

谢谢

原文由 Ishan Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 468
2 个回答

这是一个仅在满足特定条件(例如完成获取)时才重新渲染的示例。

例如,这里我们只在值达到 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'));

现场示例 在这里

原文由 Colin Ricardo 发布,翻译遵循 CC BY-SA 4.0 许可协议

所有数据类型

useState 返回一对 - 一个包含两个元素的数组。第一个元素是当前值,第二个是允许我们更新它的函数。如果我们更新当前值,则不会调用渲染。如果我们使用一个函数,那么渲染就会被调用。

 const stateVariable = React.useState("value");

stateVariable[0]="newValue"; //update without rendering
stateVariable[1]("newValue");//update with rendering

目的

如果一个状态变量被声明为一个对象,那么我们可以改变它的第一个元素。在这种情况下,不会调用渲染。

 const [myVariable, setMyVariable] = React.useState({ key1: "value" });

myVariable.key1 = "newValue"; //update without rendering
setMyVariable({ key1:"newValue"}); //update with rendering

大批

如果状态变量声明为数组,那么我们可以更改它的第一个元素。在这种情况下,不会调用渲染。

 const [myVariable, setMyVariable] = React.useState(["value"]);

myVariable[0] = "newValue"; //update without rendering
setMyVariable(["newValue"]); //update with rendering

原文由 Uku Lele 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进