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

时间:2019-01-06 22:33:13

标签: reactjs

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

由于图库将是自动滚动的条目,因此我在尝试进行后续的HTTP请求并更新状态时试图防止重新呈现组件。

谢谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

就像使用this.state.stateName = value一样简单。与使用this.setState({stateName:value})会重新渲染的情况不同,这将更改状态而无需重新渲染。例如;

class Button extends React.Component {
    constructor( props ){
        super(props);
        this.state = {
            message:"Hello World!"
        };
        this.method = this.method.bind(this);
    }
    method(e){
        e.preventDefault();
        this.state.message = "This message would be stored but not rendered";
    }
    render() {
        return (
            <div >
                {this.state.message}
                <form onSubmit={this.method}> 
                    <button type="submit">change state</button>
                </form>
            </div>
        )
    }
}
ReactDOM.render(<Button />, document.getElementById('myDiv'));

答案 2 :(得分:1)

所有数据类型

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

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
相关问题