【发布时间】:2018-06-07 17:05:00
【问题描述】:
在react router官方example中有一个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(){...}
【问题讨论】:
标签: reactjs react-router router