首页 > 解决方案 > 我需要使用什么生命周期钩子?- 反应

问题描述

情况是这样的:我有一个数据库,数据在哪里。数据由一组对象构成。这些对象具有三个属性(现在相关)。它们是:id、parentId 和状态。组件使用这些属性构建,并且组件递归地克隆自身,因此它们相互嵌套。它看起来像这样:

    
    
class Task extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            status: this.props.status
        }
    }
    
    //gets fired right after the state changed by removeTask
    static getDerivedStateFromProps(props){
        console.log("state from props")
        return{status: props.status}
    }
    
    componentDidUpdate(){
      console.log("update"); 
      this.checkDeleted()
    }
    
    checkDeleted = () => {
        if (this.state.status === 'deleted'){
            deleteTask(this.props.id) //a function which deletes from database
        }
    }
    
    tasks = () => {
        console.log("childs rendered")
        return this.props.tasks
        .filter(task => task.pId === this.props.id)
        .map(task => {
            return <Task 
                id={task.id} 
                pId={task.pId}
                status={this.state.status}
            />
        })
    }
    
    removeTask = () => {
        console.log("state changed")
        this.setState({status: 'deleted'})
    }
    
    render(){
      console.log("render")
      return(
        <div
          <button onClick={this.removeTask} />
          {this.tasks()}
        </div>
      )
    }
}

会发生什么:日志的顺序如下:

这不好,因为当状态从 removeTask() 更改时,它会在组件可以将更改后的状态传递给它的子组件之前使用 gDSFP 从道具中立即返回。但我想从道具设置状态,因为孩子们需要得到它。这里可能发生的情况是: removeTask() 被触发,设置新状态,重新渲染,子节点作为道具获得新状态,当更新发生时,删除所有组件,它是数据库中的子节点。那么什么是好的:

这个怎么赚?

标签: javascriptreactjs

解决方案


一开始我对你的订单有疑问。您的数据取决于数据库中的内容。您可能会从状态中删除并且数据库任务失败。那么为什么还要手动更新状态。只需聆听并从来自 DB 的道具中加载您的状态。当您从数据库中删除时,您的道具将被更新并重新渲染。所以基本上如果我是你,我会坚持

class Task extends React.Component{
    constructor(props){
        super(props);
    }

    //gets fired right after the state changed by removeTask
    static getDerivedStateFromProps(props){
        console.log("state from props")
        return{status: props.status}
    }

    componentDidUpdate(){
      console.log("update"); 
    }

    tasks = () => {
        console.log("childs rendered")
        return this.props.tasks
        .filter(task => task.pId === this.props.id)
        .map(task => {
            return <Task 
                id={task.id} 
                pId={task.pId}
                status={this.props.status}
            />
        })
    }

    removeTask = () => {
        console.log("state changed");
        deleteTask(this.props.id) //a function which deletes from database
    }

    render(){
      console.log("render")
      return(
        <div
          <button onClick={this.removeTask} />
          {this.tasks()}
        </div>
      )
    }
}

从上面,您可以注意到我已删除checkDeleted,因为我不需要更新我的状态。我只能依靠道具。删除设置状态状态,因为我可以只依赖 btw 计数或与 DB 同步的道具状态。


推荐阅读