如何停止render()函数,直到所有状态都将被更新?

时间:2019-01-25 14:16:39

标签: javascript reactjs

以下代码将调用render()函数三次。有没有一种方法可以等待状态中的所有三个属性都被更新,然后只调用一次render()? 也许我应该使用shouldComponentUpdate?我是ReactJS的新手。我不知道会是什么样子。 有什么想法吗?

import React from "react";

export default class MyClass extends React.Component {
  constructor() {
    super();
    this.state = {
      first: "value1",
      second: "value2",
      third: "value3"
    };
  }

  changeFirst() {
    setTimeout(() => {
      this.setState({ first: "somethingFirst" });
    }, 2000);
  }
  changeSecond() {
    setTimeout(() => {
      this.setState({ second: "somethingSecond" });
    }, 3500);
  }
  changeThird() {
    setTimeout(() => {
      this.setState({ third: "somethingThird" });
    }, 5000);
  }

  componentDidMount() {
    this.changeFirst();
    this.changeSecond();
    this.changeThird();
  }

  render() {
    return (
      <div>
        {console.log(this.state.first) +
          "\n" +
          console.log(this.state.second) +
          "\n" +
          console.log(this.state.third) +
          "\n"}{" "}
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:2)

是的,您可以使用shouldcomponentupdate

shouldComponentUpdate(nextProps, nextState){
    const { first, second, third } = this.state;
    if(first !== nextState.first && second !== nextState.second && third !== nextState.third){
        return true;
    }

    return false;
}

除非三个状态的整体都被更新,否则这将阻止组件的更新。

答案 1 :(得分:0)

您只需退出渲染功能,直到设置了所有三个变量:

import React from "react";

export default class MyClass extends React.Component {
    constructor() {
        super();
        this.state = {
            first: "",
            second: "",
            third: ""
        };
    }

    changeFirst() {
        setTimeout(() => {
            this.setState({ first: "somethingFirst" });
        }, 2000);
    }
    changeSecond() {
        setTimeout(() => {
            this.setState({ second: "somethingSecond" });
        }, 3500);
    }
    changeThird() {
        setTimeout(() => {
            this.setState({ third: "somethingThird" });
        }, 5000);
    }

    componentDidMount() {
        this.changeFirst();
        this.changeSecond();
        this.changeThird();
    }

    render() {
        if (!first || !second || !third) return (<div> Loading the vars... </div>)
        return (
            <div>
                {console.log(this.state.first) +
                    "\n" +
                    console.log(this.state.second) +
                    "\n" +
                    console.log(this.state.third) +
                    "\n"}{" "}
            </div>
        );
    }
}