首页 > 解决方案 > React - 我怎样才能在状态下只渲染一次值

问题描述

我需要做的是一个值设置状态,然后通过道具将数据发送给一个孩子,但我希望“状态”在这样做一次后忘记这一点。

this.setState({ 
    animateId: 15 //or any number of id
});

然后稍后

if(this.state.animateId){
   let idToSent = this.state.animateId;
}
<Items <...different props> animate={idToSent}/> //once after settingState - 15, 
                                        // then undefined or whatever with every next time

我想取这个值一次,通过 props 发送它,然后不管它,无论哪种方式。

有没有办法做到这一点,除了再次改变状态中的那个值,因为这会导致不必要的渲染?

标签: reactjs

解决方案


我们可以在任务完成后将其设置为 undefined

this.setState({ doSomething: undefined });


推荐阅读