How to use 'this.props.params' in React?

我只是一个虾纸丫 提交于 2020-05-17 06:50:04

问题


I send a certain id (idValue) to my component and use it like this:

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

But sometimes this component opens without any input parameters (without idValue) and I got this error:

TypeError: Cannot read property 'idValue' of undefined

How can I fix it?

I've tried to use typeof, but it was unsuccessful

In the component from which the value is transferred, I use context router


回答1:


static defaultProps = {
    params:{}
}



回答2:


The error tells us that this.props.params is undefined sometimes (probably because no params was passed to the component at all).

How can I fix it?

It depends on whether you want to call this.onHandleFetch if there's no params.idValue.

If you don't, use an 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.




回答3:


Add appropriate default props to the component where you are trying to access the params e.g.

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.

  1. with params <MyComponent params={{ idValue: 1 }} /> will use the params passed here.
  2. without params <MyComponent /> will fallback to the defaultProps above.

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.

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

Alternatively, you can pass a default value if idValue is not defined e.g.

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


来源:https://stackoverflow.com/questions/52850512/how-to-use-this-props-params-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!