【问题标题】:react router property value反应路由器属性值
【发布时间】: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 (
            // ...
        )
    }
}
  1. 在类的第一行

    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?
    }
    
  2. 第二个问题是:this.props 的值在以下位置是否相同?

    previousLocation = this.props.location
    
    componentWillUpdate(nextProps) {...}
    
    render(){...}
    

【问题讨论】:

    标签: reactjs react-router router


    【解决方案1】:

    对于1。因为previousLocation是类的属性,所以不需要const。我认为他们正在使用transform-class-properties 插件。见here

    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' 将是接收更新 props 之前的旧 props。在渲染中是渲染时的“道具”。当您控制台日志时 this.props 将具有不同的值,但含义是相同的。

    例如:

    你有以下代码:

    <Component property={this.state.value} />
    

    并且 state.value 为 5。然后将调用 constructor,然后调用 renderthis.props.value 将是 5。

    在父组件中,如果状态改变:

     setState({value: 6}). 
    

    然后componentWillUpdate 将被调用。 this.props.value 是旧的 props,值为 5,newProps.value 将是 6。然后 props 将被更新,render 将被调用。在render 中,this.props.value 为 6。

    【讨论】:

    • 感谢@Daniel Tran,非常感谢您的帮助!您对问题 1 的回答似乎是正确的。根据您的问题 1 的答案,我可以像您一样修改代码和 console.log(previousLocation) 并查看它的值。但是,您对问题 2 的回答似乎是错误的。当您导航到不同的位置时,constructor()、componentWillUpdate() 和 render() 中的快速 console.log(this.props) 会显示不同的值,请验证我是否正确。
    • 更新答案澄清
    • 好的,现在很清楚了,我会接受你的回答。不过语法可能会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2019-10-18
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多