Javascript 使用React生命周期方法为子组件中的每个用户发出POST请求并更新数据库

Javascript 使用React生命周期方法为子组件中的每个用户发出POST请求并更新数据库,javascript,reactjs,redux,react-component,react-lifecycle,Javascript,Reactjs,Redux,React Component,React Lifecycle,下表显示了上个月用户工资的详细信息。单击“更新””按钮时,系统将检索本月的必要数据,计算新的薪资和财产,并更新子组件表值。子组件也有其他子组件按钮。 使用新值更新表raws时,“需要为每个用户发出post请求,并迭代更新数据库”。在这里,渲染子组件及其子组件时,会发生无限循环(infinity POST请求更新DB) 你能建议一种方法来更新数据库中每个用户的详细信息吗。在子组件“RowComponent”中调用Redux操作函数(this.props.updateUserLog(newUserL

下表显示了上个月用户工资的详细信息。单击“更新””按钮时,系统将检索本月的必要数据,计算新的薪资和财产,并更新子组件表值。子组件也有其他子组件按钮。 使用新值更新表raws时,“需要为每个用户发出post请求,并迭代更新数据库”。在这里,渲染子组件及其子组件时,会发生无限循环(infinity POST请求更新DB

你能建议一种方法来更新数据库中每个用户的详细信息吗。在子组件“RowComponent”中调用Redux操作函数(this.props.updateUserLog(newUserLog.handle,userDetails))的方法。重新呈现其子级时,POST请求不得发送循环

~父组件~

从“./redux/actions/dataActions”导入{getDriverCommissionAlcohol};
类DriverPerformance扩展组件{
构造函数(props={}){
超级(道具);
此.state={
新闻界:错,
};
}
更新性能=(事件)=>{
this.setState({press:true});
this.props.getDriverCommissionCohol(月、年);
};
render(){
常数{
数据:{
驱动程序:{用户、月份、年份、创建日期},
性能:{driverCommission,status},
},
UI:{loadingOffScrean},
}=这是道具;
让DriverCommissionResults={};
if(this.state.press){
设combinedUser={};
让最近的=[];
if(Object.keys(DriverCommissionResults).length>0){
组合用户forEach((filteredPerson)=>{
最近的推(
);
});
}否则{
最近的=(
{user.map((filteredPerson)=>(
))}
);
}
}
返回(
更新
{最近}
);
}
}
~子组件~

从“./redux/actions/dataActions”导入{updateUserLog};
类RowComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
句柄:“”,
创建数据:“”,
排名:0,
年份:“,
月份:“,
};
}
组件将接收道具(){
常量newUserLog={
把手:这个。道具。把手,
createdAt:new Date().toISOString(),
排名:NewRankingCalculate,
年份:这个。道具。年份回顾?这个。道具。年份回顾:这个。道具。年份,
月份:this.props.monthRetrive?this.props.monthRetrive:“”,
};
this.mapUserDetailsToState(newUserLog);
}
mapUserDetailsToState=(newUserLog)=>{
这是我的国家({
句柄:newUserLog.handle?newUserLog.handle:“”,
createdAt:newUserLog.createdAt?newUserLog.createdAt:“”,
排名:newUserLog.ranking?newUserLog.ranking:“”,
年份:newUserLog.year?newUserLog.year:“”,
月份:newUserLog.month?newUserLog.month:“”,
});
const userDetails={
句柄:newUserLog.handle,
createdAt:newUserLog.createdAt,
排名:newUserLog.ranking,
年份:newUserLog.year,
月份:newUserLog.month,
};
this.props.updateUserLog(newUserLog.handle,userDetails);
};
render(){
常数{
成员:{用户名,年,月,工资},
}=这是道具;
让行动=(
);
{initialSalary}
{this.state.salary!==0?this.state.salary:salary}
{action}
;
}
}
期望值: 通过调用子组件生命周期方法中的POST requests函数,为每个用户更新DB表。停止无限循环POST请求。并在更换道具后提出post请求

  • 我注意到,
    if(Object.keys(DriverCommissionResults).length>0)
    ParentComponent中的表达式将始终为false,对吗?因为
    DriverCommissionResults
    只是一个空对象,所以在此检查之前初始化了两行:)
  • 尝试从
    PureComponent
    扩展
    RowComponent
    ,这将确保
    RowComponent
    仅在某些道具确实更改时才会重新播放(请参阅文档:)

  • 但我不喜欢你在这里做的一切。 基本上,您可以在单击按钮时更改ParentComponent的状态,并在组件接收道具时产生副作用(在本例中调用redux)。 我建议:

  • 在代码> PARTECTIONS组件<代码> -在Button.onClick的中间做副作用(UPDATE DB)(保持状态更改,因为您可能需要某种等待指示符)。
  • RowComponent
    -如果你正在做一些副作用-更好的地方是
    componentDidMount
    componentDidUpdate
    (但在第二个地方,你最好总是检查道具是否真的与以前的道具不同!)

  • 1. <代码>如果(Object.keys(DriverCommissionResults).length>0)不为空。它包含值。我没有添加所有代码。正确更新表中的值。没问题。但是当为DB
    this.props.updateUserLog(newUserLog.handle,userDetails)的POST数据调用redux函数时
    infinity post请求循环正在发生:(按照您的说明修复了此问题。)谢谢。@ViduminiKulathunga很高兴听到这个消息!如果您将我的答案标记为“最佳答案”(绿色勾选图标):)祝您编码愉快!
    import { getDriverCommissionAlcohol } from "../redux/actions/dataActions";
    
    class DriverPerfomance extends Component {
      constructor(props = {}) {
        super(props);
    
        this.state = {
          press: false,
        };
      }
    
      UpdatePerformance = (event) => {
        this.setState({ press: true });
        this.props.getDriverCommissionAlcohol(month, year);
      };
    
      render() {
        const {
          data: {
            drivers: { user, month, year, createdAt },
            performance: { driverCommission, alcoholStatus },
          },
          UI: { loadingOffScrean },
        } = this.props;
    
        let DriverCommissionResults = {};
    
        if (this.state.press) {
          let combinedUser = {};
          let recent = [];
    
          if (Object.keys(DriverCommissionResults).length > 0) {
            combinedUser.forEach((filteredPerson) => {
              recent.push(
                <RowComponent
                  key={filteredPerson.userId}
                  handle={filteredPerson.username}
                  monthRetrive={this.state.month}
                  yearRetrive={this.state.year}
                  month={month}
                  year={year}
                  drunkenPesentage={filteredPerson.drunkenPesentage}
                  press={true}
                  newMonthCalculationDone={true}
                />
              );
            });
          } else {
            recent = (
              <Fragment>
                {user.map((filteredPerson) => (
                  <RowComponent
                    key={filteredPerson.userId}
                    handle={filteredPerson.username}
                    month={month}
                    year={year}
                    press={false}
                    newMonthCalculationDone={false}
                  />
                ))}
              </Fragment>
            );
          }
        }
    
        return (
          <Fragment>
            <Button disabled={loadingOffScrean} onClick={this.UpdatePerformance}>
              Update
            </Button>
            <table>
              <thead>
                <tr>
                  <th></th>
                </tr>
              </thead>
              <tbody>{recent}</tbody>
            </table>
          </Fragment>
        );
      }
    }
    
    import { updateUserLog } from "../redux/actions/dataActions";
    
    class RowComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          handle: "",
          createdAt: "",
          ranking: 0,
          year: "",
          month: "",
        };
      }
    
      componentWillReceiveProps() {
        const newUserLog = {
          handle: this.props.handle,
          createdAt: new Date().toISOString(),
          ranking: NewRankingCalculate,
          year: this.props.yearRetrive ? this.props.yearRetrive : this.props.year,
          month: this.props.monthRetrive ? this.props.monthRetrive : "",
        };
    
        this.mapUserDetailsToState(newUserLog);
      }
    
      mapUserDetailsToState = (newUserLog) => {
        this.setState({
          handle: newUserLog.handle ? newUserLog.handle : "",
          createdAt: newUserLog.createdAt ? newUserLog.createdAt : "",
          ranking: newUserLog.ranking ? newUserLog.ranking : "",
          year: newUserLog.year ? newUserLog.year : "",
          month: newUserLog.month ? newUserLog.month : "",
        });
    
        const userDetails = {
          handle: newUserLog.handle,
          createdAt: newUserLog.createdAt,
          ranking: newUserLog.ranking,
          year: newUserLog.year,
          month: newUserLog.month,
        };
    
        this.props.updateUserLog(newUserLog.handle, userDetails);
      };
    
      render() {
        const {
          member: { username, year, month, salary },
        } = this.props;
        let action = (
          <DrunkenLog
            handle={username}
            month={this.state.month !== "" ? this.state.month : month}
            year={this.state.year !== "" ? this.state.year : year}
          />
        );
        <tr>
          <td>{initialSalary}</td>
          <td>{this.state.salary !== 0 ? this.state.salary : salary}</td>
          <td>{action}</td>
        </tr>;
      }
    }