首先你应该在
location
location.state
因为它们可能是
undefined
因为此方法是在父组件的状态或属性中的任何更新之后立即调用的。你可以看到
the Official doc
. 你应该这样做:
componentDidUpdate(prevProps) {
if (this.props.location && this.props.location.state && typeof this.props.location.state.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...
Optional chaining
:
componentDidUpdate(prevProps) {
if (typeof this.props.location?.state?.serial === "undefined"){
const database = db.ref().child("Devices/" + prevProps.location.state.serial);
...