[英]How does the child component receive props from the parent component without listening for the lifecycle method?
要更新子組件中的props
對象,通常使用生命周期方法ComponentWillReceiveProps
。 但我意識到子組件的props
可以在不監聽ComponentWillReceiveProps
情況下更新。
例如,在以下名為App
的組件中,子組件Comp
能夠在不偵聽生命周期方法ComponentWillReceiveProps
情況下接收props
。
主要App
組件:
import React from 'react';
import ReactDOM from 'react-dom';
import {Comp} from "./comp";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
componentDidMount() {
this.setState({
counter: 100
})
}
incrementCounter() {
this.setState({
counter: this.state.counter + 1
})
}
render() {
return (
<div>
<button onClick={this.incrementCounter}>Increment</button>
<br />
<br />
<Comp counter={this.state.counter}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
和子Comp
組件:
import React from 'react';
export class Comp extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidUpdate(prevProps, prevState) {
console.log("prev props ", prevProps);
console.log("prev state", prevState)
}
render() {
return <span>Props received: {JSON.stringify(this.props)}</span>
}
}
這也是我准備的上述代碼的工作演示
您將看到子組件Comp
接收屬性counter
而無需偵聽任何生命周期方法。
這是什么意思? 我錯過了什么嗎?
componentWillReceiveProps()
是一個不推薦使用的生命周期方法,當組件即將接收新的 props 時會觸發它。 但是,它無法控制組件是否實際接收這些道具。
https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops
無論是否執行componentWillReceiveProps()
,組件都會從父級接收更新的道具。
import React from 'react';
export class Comp extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
console.log(this.props.counter) //still gets printed with new props data
return <span>Props received: {JSON.stringify(this.props)}</span>
}
}
請注意,道具嚴格從父組件傳遞到子組件。
當父組件通過狀態更改重新渲染時,它也會重新渲染子組件並傳遞更新的道具。 現在子組件可以訪問這些新的 props,它們會經歷 React 事件的生命周期。
像componentDidUpdate()
和componentWillReceiveProps()
這樣的事件允許你執行一些額外的邏輯,但它們不是組件接收道具或重新渲染所必需的。 無論使用情況如何,組件都將重新渲染。
此外,子組件可以通過內部狀態更新來更新自身,就像任何基於類的組件一樣。
每次在父節點/組件上執行 setState 時,它都會使用最新的 props 重新渲染所有子組件。 所以基本上每當父組件被重新渲染時,該節點的所有子組件都會被重新渲染。
默認行為是在每次狀態更改時重新渲染,在絕大多數情況下,您應該依賴默認行為。
如果您不希望您的子組件在某些情況下重新渲染,您可以使用 shouldComponentUpdate 生命周期。 這個生命周期只是一個性能優化。 閱讀 shouldcomponentupdate
還可以考慮使用 PureComponent 而不是組件。 它對 props 和 state 進行淺層比較,並減少您跳過必要更新的機會。 閱讀 PureComponent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.