#javascript #reactjs #react-native
Вопрос:
Я пытаюсь использовать хуки в этой функции, но сначала мне нужно преобразовать этот компонент класса в функцию. Я изо всех сил пытаюсь понять, как методы визуализации и конструкторы работают в функциях, и мне не помешала бы помощь в понимании.
Класс, который я пытаюсь преобразовать:
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);
Комментарии:
1. digitalocean.com/community/tutorials/… дает довольно достаточное объяснение
Ответ №1:
Имейте в виду эти:
- В классе вам нужен конструктор. В функции функция сама по себе является конструктором.
- Компонент функции получает реквизиты в качестве параметра.
- В вашем функциональном компоненте вы не используете резервный ключ
this
. - Крючок useEffect работает как
componentDidMount
иcomponentDidMethod
вместе. - если у вас есть определенный метод (здесь его нет в вашем коде, но он может быть применен в другом), вы можете определить этот метод как функцию в компоненте функции.
Итак, ваш код может привести к чему-то вроде этого:
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>
);
}