简体   繁体   English

我需要使用哪个生命周期挂钩? -反应

[英]What lifecycle hook i need to use? - react

The situation is this: i have a database, where the data is. 情况是这样的:我有一个数据库,数据在哪里。 The data is structured with an array of objects. 数据由对象数组构成。 The objects have three properties (which are relevant now). 这些对象具有三个属性(现在相关)。 These are: id, parentId, and status. 它们是:id,parentId和状态。 The components build up with these properties, and the component clones itself recursively, so they are nested within each other. 组件使用这些属性构建,并且组件以递归方式克隆自身,因此它们彼此嵌套。 It looks like this: 看起来像这样:

 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> ) } } 

What happens: the order of the logs are the next: 发生了什么:日志的顺序是下一个:

  • state changed (removeTask()) 状态已更改(removeTask())
  • state from props (gDSFP()) 道具的状态(gDSFP())
  • render 给予
  • childs rendered (tasks() fired inside render()) 渲染的子级(在render()内部触发的task())
  • update (componentDidUpdate()) 更新(componentDidUpdate())

This isn't good, because when the state changed from removeTask(), it gets right back from the props with gDSFP, before the component can pass the changed state to it's childs. 这不是很好,因为当状态从removeTask()更改时,它会在组件可以将更改后的状态传递给其子项之前从gDSFP道具返回。 But i want to set the state from the props, because the childs need to get it. 但是我想从道具设置状态,因为孩子们需要得到它。 What could happen here is: the removeTask() fired, sets the new state, rerender, the childs get the new status as a prop, and when the update happens, deletes all the component, and it's child from the database. 这里可能发生的事情是:触发removeRemoveTask(),设置新状态,重新渲染,子级将新状态作为prop,并且当更新发生时,删除所有组件,并将其从数据库中删除。 So what will be good: 那么有什么好处:

  • click happened, set new state 点击发生,设置新状态
  • render 给予
  • render childs, set they status prop to the state 渲染孩子,将他们的状态道具设置为州
  • check if the status is "deleted" 检查状态是否为“已删除”
  • set state from props if it's changed, and rerender 从道具设置状态(如果已更改),然后重新渲染

How to earn this? 如何赚钱?

I have problem with your order to begin with. 首先,我对您的订单有疑问。 Your data depends on whats in the DB. 您的数据取决于数据库中的内容。 You might delete from the state and the DB task failed. 您可能会从状态中删除,并且数据库任务失败。 So why bother updating the state manually. 那么,为什么要手动更新状态呢? Just listen and load your state from props that come from DB. 只需从DB发出的道具中监听并加载状态即可。 when you delete from the DB, your props will be updated and re-render will occur. 当您从数据库中删除时,您的道具将被更新并重新渲染。 So basically if i were you , i would stick with 所以基本上如果我是你,我会坚持

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>
      )
    }
}

from the above, you can notice i removed checkDeleted because i don't need to update my state. 从上面的内容中,您可以注意到我删除了checkDeleted因为我不需要更新状态。 I can just rely on props. 我可以依靠道具。 Remove set state status because i can just rely on props sttaus which btw tally or is in sync with DB. 删除设置状态状态,因为我只能依靠道具sttaus,提示道具或与数据库同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要澄清反应的状态和生命周期 - I need clarification for State and Lifecycle of react React:我应该在哪个生命周期挂钩上解析新接收到的数据? - React: On which lifecycle hook should I parse new received data? 我应该使用什么生命周期方法来监听 state 的变化并在反应 class 组件中相应地更新其他 state - What lifecycle method should i use to listen for changes in state and update other state accordingly in react class component 通过服务更改componentInstance属性中的集合时,需要有角度的生命周期挂钩吗? - What's an angular lifecycle-hook need when changing sets in componentInstance property by service? 没有正确使用反应生命周期 - not proper use of react lifecycle React 组件生命周期钩子中`this` 的范围问题 - Scope Issue With `this` Inside React Component Lifecycle Hook React生命周期方法(例如componentWillReceiveProps)的典型用例是什么 - What are typical use cases for React lifecycle methods like componentWillReceiveProps 如何在MobX中使用React生命周期方法? - How do I use React lifecycle methods with MobX? 如何使用带有反应钩子的互斥锁? - How can I use a Mutex with a react hook? 我可以在反应钩子中使用循环吗? - Can I use a loop inside a react hook?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM