如何使此setState函数不递归

时间:2018-08-29 17:45:15

标签: javascript reactjs

我正在学习反应,并且还处于早期阶段。我试图将一个对象添加到从另一个组件到另一个组件的数组中。我能够使用道具来实现这一点,但是现在当我尝试在this.state中设置它时,setState再次调用了render函数,从而再次触发了该函数。我可以使用按钮解决此问题,但我不想这样做。有更好的方法吗?

getData() {
    if (this.props.data.employeeData !== undefined) {
        if (this.props.isNewEmployee === "true") {
            this.setState({
                isNewEmployee: "true",
            });
            setTimeout(() => {
                if (this.state.isNewEmployee === "true") {
                    console.log(this.props.data.employeeData.firstName);
                    var joined = this.state.EmployeesList.concat(this.props.data.employeeData);
                    this.setState({
                        EmployeesList: joined,
                        isNewEmployee: "false",
                    })
                }
                else {
                    console.log("Don't know what's happening anymore");
                }
            }, 100);
        }
        else {
            console.log("No new employee added");
        }
    }
    else {
        console.log("Something went wrong");
    }
}

render() {
    return (
        <div>
            {this.getData()}
            {this.renderTable()}
            {this.renderFloatingActionButton()}
        </div>
    )
}

1 个答案:

答案 0 :(得分:1)

如果props的意图是将新数据添加到表中,我将在这些行中进行一些操作。

componentWillReceiveProps(nextProps) {
    if (this.props.data.employeeData && nextProps.isNewEmployee !== this.props.isNewEmployee) {
      console.log(this.props.data.employeeData.firstName);
      var joined = this.state.EmployeesList.concat(this.props.data.employeeData);
      this.setState({
        EmployeesList: joined,
        isNewEmployee: "false",
      });
    } else {
      console.log("No new employee added");
    }
}
render() {
    return (
        <div>
            {this.renderTable()}
            {this.renderFloatingActionButton()}
        </div>
    )
}