I was working on some React Native code (shown below):
checkPars = () => {
var params = useParams();
if (params) {
if (params.photoId) {
this.setState({
photoId: params.photoId
});
this.fetchComments(params.photoId);
}
}
};
And I got this error:
Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
I looked on the page, but I was confused. It said that I should put the hook on the top level of a functional component, or at the top level of a custom Hook. But my code was in a class, not a function! What should I do?
CodePudding user response:
You can't use React Hooks
in Class
Components only Functional
Components
It's what the Error is telling you. So ask yourself does this really have to be a Class Component? or can you just use a Functional One? The Code you showed us doesn't help to determine what option is best for you. Chances are It's the later.
CodePudding user response:
According to React hooks naming convention, this function called useParams()
is treated as hook even if it's a normal function.
in case you are using React Navigation, you can access screen parameters as props as below
class Myscreen extends React.Component {
checkPars = () => {
const { route, navigation } = props;
const params = route.params;
if (params) {
if (params.photoId) {
this.setState({
photoId: params.photoId,
});
this.fetchComments(params.photoId);
}
}
};
render() {
// Render UI...
}
}