如何使这个setState函数非递归

问题描述 投票:1回答:1

我正在学习反应,并处于非常早期的阶段。我试图将一个对象添加到另一个组件到另一个组件的数组中。我能够使用道具实现这一点,但现在当我尝试在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>
    )
}
javascript reactjs
1个回答
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>
    )
}

推荐问答