如何更新反应状态而不重新渲染组件?

Ish*_*tel 2 reactjs

我正在构建一个图库应用程序,我需要创建多个HTTP请求来拉取图库和条目(图像和视频).

由于库将自动滚动条目,我试图阻止重新呈现组件,当我发出后续HTTP请求并更新状态.

谢谢

Uku*_*ele 22

所有数据类型

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

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

stateVariable[0]="newValue"; //update without rendering
stateVariable[1]("newValue");//update with rendering
Run Code Online (Sandbox Code Playgroud)

目的

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

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

myVariable.key1 = "newValue"; //update without rendering
setMyVariable({ key1:"newValue"}); //update with rendering
Run Code Online (Sandbox Code Playgroud)

大批

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

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

myVariable[0] = "newValue"; //update without rendering
setMyVariable(["newValue"]); //update with rendering
Run Code Online (Sandbox Code Playgroud)

  • 虽然此代码可以提供问题的解决方案,但最好添加有关其工作原理/原因的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。当代码得到解释时,您也可能会得到用户的积极反馈/支持。 (2认同)

cr4*_*r4z 15

没有一个答案适用于 TypeScript,所以我将添加这个。一种方法是改用 u​​seRef 挂钩并通过访问“current”属性直接编辑值。看这里:

const [myState, setMyState] = useState<string>("");

变成

let myState = useRef<string>("");

您可以通过以下方式访问它:

myState.current = "foobar";

到目前为止我还没有看到任何缺点。但是,如果这是为了防止子组件更新,则应考虑使用 useMemo 挂钩来提高可读性。useMemo 挂钩本质上是一个给出显式依赖项数组的组件。


Col*_*rdo 10

这是仅在满足特定条件(例如,完成提取)时重新呈现的示例.

例如,这里我们只在值达到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'));
Run Code Online (Sandbox Code Playgroud)

这里有实例.