[英]react router property value
在React Router官方示例中 ,有一個ModalSwitch類,其中包含以下代碼
class ModalSwitch extends React.Component {
previousLocation = this.props.location
componentWillUpdate(nextProps) {
const {location} = this.props
if (
nextProps.history.action !== 'POP' &&
(!location.state || !location.state.modal)
) {
this.previousLocation = this.props.location
}
}
render() {
const {location} = this.props
const isModal = !!(
location.state &&
location.state.modal &&
this.previousLocation !== location
)
return (
// ...
)
}
}
在課程的第一行
previousLocation = this.props.location
為什么以這種方式聲明previousLocation
?
我以為我應該在previousLocation
添加const
,但這是錯誤的,因為會出現語法錯誤,為什么?
const previousLocation = this.props.location // syntax error
或者我以為我應該將previousLocation
放在constructor
函數中,但這又是錯誤的
constructor(){ super(); this.previousLocation = this.props.location // this.props would be undefined, why? }
第二個問題是: this.props
的值在以下位置是否相同?
previousLocation = this.props.location componentWillUpdate(nextProps) {...} render(){...}
對於1.。因為previousLocation
是類的屬性,所以不需要const。 我認為他們正在使用transform-class-properties
插件。 看這里
ES編譯器將編譯代碼以將屬性初始化為類構造函數。
constructor
將收到一個props
字典,因此您需要執行以下操作:
constructor(props){
super(props);
this.previousLocation = this.props.location // this.props would be assign by super(props), in your code, props is undefined.
this.previousLocation = props.location
}
對於2。答案是肯定的。 更准確:所有對象都指向當前組件的“ props”屬性。 在構造函數中,原始道具從父組件傳遞。 在“ componentWillUpdate”中,“ props”將是接收更新道具之前的舊道具。 在渲染中,渲染時是“道具”。 在控制台日志中,this.props的值將不同,但含義相同。
例如:
您有以下代碼:
<Component property={this.state.value} />
並且state.value為5。然后將調用constructor
,然后render
。 this.props.value
將為5。
在父組件中,如果狀態更改:
setState({value: 6}).
然后componentWillUpdate
將被調用。 this.props.value
是舊的道具,值為5, newProps.value
將為6。然后將更新props
並調用render
。 在render
,this.props.value為6。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.