问题
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.
- with params
<MyComponent params={{ idValue: 1 }} />will use the params passed here. - 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