【发布时间】:2020-02-03 15:01:47
【问题描述】:
我正在尝试在 React 中实现 MVVM(我正在学习的课程的要求)。我正在为视图使用功能组件,并为 ViewModel 提供打字稿类。但是,当 ViewModel 中的属性更新时,我的组件不会重新渲染。
这是一个应该在登录和注册表单之间切换的页面的简单示例。 setCurrentForm 被正确调用并且 ViewModel 中的值会更新,但不会更改 View。
// AuthView.tsx
const AuthView: React.FC = () => {
const VM = new AuthViewModel();
let form;
if (VM.currentForm === FORMS.SignUp) {
// Toggles the current form between FORMS.SignUp and FORMS.Login
form = <SignUpForm setCurrentForm={() => VM.setCurrentForm()} />
} else {
form = <LoginForm setCurrentForm={() => VM.setCurrentForm()} />
}
return (
<Container>
{/* Sign up card */}
<div className="mt-12">
{form}
</div>
</Container>
);
}
export default AuthView;
// AuthViewModel.tsx
export default class AuthViewModel {
email: string = "";
password: string = "";
currentForm: FORMS = FORMS.SignUp;
setCurrentForm() {
console.log("Setting form in VM");
if (this.currentForm === FORMS.SignUp) {
console.log("Switching to login")
this.currentForm = FORMS.Login;
} else if (this.currentForm === FORMS.Login) {
console.log("Switching to signup")
this.currentForm = FORMS.SignUp;
}
}
}
我可以通过更新任意值来强制使用钩子重新渲染,但我认为有更好的方法来做到这一点。你怎么认为?
【问题讨论】:
标签: reactjs typescript mvvm