React state和props注意

想在state中,直接用props的参数的值,
比如

state={
  longitude:this.props.formData.longitude,
  latitude:this.props.formData.latitude
}

但是报错,说formData没定义,明明已经传入了的,后来发现了原因,因为我同时用了两个

class A extends React.Component{
    constructor(){
          xxxxxxxx

    }
    state={
       longitude:this.props.formData.longitude,
       latitude:this.props.formData.latitude
    }
}

我一开始以为是state没有在constructor中写,但是放进去了也照样报错
仔细检查后发现

constructor(props){
          super(props)

    }

如果用constructor的话,这两个必写,接收props,并super,不然props都接收不到

转载于:https://www.jianshu.com/p/f0bbbe01107c

猜你喜欢

转载自blog.csdn.net/weixin_34126557/article/details/91095930