Reputation: 87
I'm trying to use hooks in this function, but first I need to convert this class component into a function. I'm struggling to understand how render methods and constructors work in functions and could use some help understanding.
Class that I'm trying to convert:
class MainSwitchNavigator extends Component {
constructor(props) {
super(props);
const { location, history } = this.props;
this.previousLocation = location;
navigator.setTopHistory(history);
}
render() {
const { classes } = this.props;
return (
<main>
<div className={classes.container}>
<Switch>
<Route path="/" exact component={OnboardingScreen} />
<Route path="/consent" component={ConsentScreen} />
<Route path="/privacy-policy" component={PrivacyPolicyScreen} />
<Route path="/term-service" component={TermOfServiceScreen} />
<Route path="/sign-in" component={SignInScreen} />
<Route path="/sign-up" component={SignUpScreen} />
<Route path="/send-code" component={SendCodeScreen} />
<Route path="/verify-code" component={VerifyCodeScreen} />
<Route path="/new-password" component={NewPasswordScreen} />
<Route path="/home" component={MasterContainer} />
<Route path="/covid-testing-consent" component={CovidTestingConsentScreen} />
<Route component={NoMatch} />
</Switch>
<ToastContainer />
</div>
</main>
);
}
}
const NoMatch = ({ location }) => (
<div>
<h3>Page not found</h3>
</div>
);
export default withStyles(styles)(MainSwitchNavigator);
Upvotes: 0
Views: 92
Reputation: 434
Keep in mind these:
this
.componentDidMount
and componentDidMethod
together.So, your code may be result in something like this:
function MainSwitchNavigator({location, history, classes}) {
React.useEffect(() => {
// this code was in your constructor, so I assume must be executed only once
navigator.setTopHistory(history);
}, []) // the empty array ensures the useEffect going to executes only one time.
return (
<main>
<div className={classes.container}>
<Switch>
<Route path="/" exact component={OnboardingScreen}/>
<Route path="/consent" component={ConsentScreen}/>
<Route path="/privacy-policy" component={PrivacyPolicyScreen}/>
<Route path="/term-service" component={TermOfServiceScreen}/>
<Route path="/sign-in" component={SignInScreen}/>
<Route path="/sign-up" component={SignUpScreen}/>
<Route path="/send-code" component={SendCodeScreen}/>
<Route path="/verify-code" component={VerifyCodeScreen}/>
<Route path="/new-password" component={NewPasswordScreen}/>
<Route path="/home" component={MasterContainer}/>
<Route path="/covid-testing-consent" component={CovidTestingConsentScreen}/>
<Route component={NoMatch}/>
</Switch>
<ToastContainer/>
</div>
</main>
);
}
Upvotes: 3