简体   繁体   English

如何在React中使用'this.props.params'?

[英]How to use 'this.props.params' in React?

I send a certain id (idValue) to my component and use it like this: 我将某个id(idValue)发送到我的组件,并像这样使用它:

componentDidMount() {
    this.onHandleFetch(this.props.params.idValue);
  }

But sometimes this component opens without any input parameters (without idValue) and I got this error: 但是有时候这个组件打开时没有任何输入参数(没有idValue),我得到了这个错误:

TypeError: Cannot read property 'idValue' of undefined

How can I fix it? 我该如何解决?

I've tried to use typeof , but it was unsuccessful 我尝试使用typeof ,但未成功

In the component from which the value is transferred, I use context router 在从中传输值的组件中,我使用上下文路由器

The error tells us that this.props.params is undefined sometimes (probably because no params was passed to the component at all). 该错误告诉我们有时undefined this.props.params (可能是因为根本没有params传递给组件)。

How can I fix it? 我该如何解决?

It depends on whether you want to call this.onHandleFetch if there's no params.idValue . 如果没有params.idValue ,则取决于是否要调用this.onHandleFetch

If you don't, use an if : 如果不这样做,请使用if

componentDidMount() {
  if (this.props.params && this.props.params.idValue) {
    this.onHandleFetch(this.props.params.idValue);
  }
}

If you do, providing some replacement value, then: 如果这样做,提供一些替换值,则:

componentDidMount() {
  this.onHandleFetch((this.props.params && this.props.params.idValue) || replacementValue);
}

Both of those assume idValue won't be 0 . 这两个都假设idValue不会为0

static defaultProps = {
    params:{}
}

Add appropriate default props to the component where you are trying to access the params eg 在尝试访问参数的组件中添加适当的默认道具,例如

MyComponent.defaultProps = {
  params: {}
};

This will mean that when you try to access params from componentDidMount() , this.props.params will not be empty if you did not pass in an object for params like so when using the component. 这意味着当您尝试从componentDidMount()访问params时,如果未像使用该组件那样将对象传递给params,则this.props.params不会为空。

  1. with params <MyComponent params={{ idValue: 1 }} /> will use the params passed here. 带有参数<MyComponent params={{ idValue: 1 }} />将使用此处传递的参数。
  2. without params <MyComponent /> will fallback to the defaultProps above. 没有参数的<MyComponent />将回退到上面的defaultProps。

You will only need to check for the presence of ID in that case to make sure that your component only makes the fetch if an idValue is defined in the params. 在这种情况下,您只需要检查ID的存在即可确保只有在params中定义了idValue ,您的组件才进行获取。

componentDidMount() {
    const { params } = this.props;
    if (params.idValue)
        this.onHandleFetch(params.idValue);
    }
}

Alternatively, you can pass a default value if idValue is not defined eg 或者,如果未定义idValue,则可以传递默认值,例如

componentDidMount() {
    const { params } = this.props;
    this.onHandleFetch(params.idValue || -1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM