[英]How to skip the update of state inside getDerivedStatefromProps() in childComponent only for the first time of rendering the childComponent
嗨,我是 Reactjs 的新手。 我希望在每次加載此組件時將以下 childComponent 的 {this.state.data} 遞增 5。 所以我在 static 方法 getDerivedStateFromProps(props,state) 但第一次加載 {this.state.data} 時應該是我定義的初始值(這里是 0)。 所以我期待下面的行 output 從 0 開始遞增 5(我定義的初始值)
來自 ClassChild 的數據:{data}
預期 Output:來自 ClassChild 的數據:0 來自 ClassChild 的數據:5 來自 ClassChild 的數據:10 來自 ClassChild 的數據:15
實際 Output:來自 ClassChild 的數據:5 來自 ClassChild 的數據:10 來自 ClassChild 的數據:15 來自 ClassChild 的數據:20
無論如何要跳過getDerivedStateFromProps(props,state)的第一次執行,而不是在構造函數中定義-5值以獲得預期的output?
class ClassChild extends Component{
constructor(props){
super(props)
console.log("ClassChild constructor()")
this.state = {
data : 0
}
}
static getDerivedStateFromProps(props,state){
console.log("ClassChild getDerivedStateFromProps()")
return {
data : state.data + props.childIncState
}
}
render(){
const {count, childIncState} = this.props
const {data} = this.state
return(
<div>
<div>Count from ClassParent : {count}</div>
<div>Value to be incremented in ClassChild : {childIncState}</div>
<div>Data from ClassChild : {data}</div>
{console.log("ClassChild render()")}
</div>
)
}
}
export default ClassChild;```
您應該使用componentDidUpdate() 。 初始渲染不調用它。
這是一個例子:
componentDidUpdate(prevProps) {
if(prevProps.childIncState !== this.props.childIncState) {
setState({data: this.state.data + props.childIncState});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.