简体   繁体   English

如何在React中强制重新渲染功能组件?

[英]How to force re-render function component in React?

I would like to re-render my function component when one of the function's variable is changed. 当函数的变量之一更改时,我想重新渲染函数组件。 Importantly this variable does not comes with props. 重要的是,此变量不随prop一起提供。

I am building a simple registration form with Material UI and React 16.8. 我正在使用Material UI和React 16.8构建一个简单的注册表单。 It comes with the hooks API that I am trying to use. 它随附了我尝试使用的hooks API。 The thing is that I would like to re-render my component when result of the input field validation changed. 问题是,当输入字段验证的结果更改时,我想重新渲染组件。

export default function Register(props) {
 let emailError = false;
 const [email, setEmail] = useState('');
 const validateEmail = (email) => {
    if(email) {
      emailError = false;
    } else {
      emailError = true; // How to force re-render if email is not valid? 
    }
 } 

 return (<div>
            <TextField
                  error={emailError}
                  variant="outlined"
                  required
                  fullWidth
                  id="email"
                  label="Email Address"
                  onKeyUp={(ev) => validateEmail(ev.target.value)}
                  onChange={(ev) => setEmail(ev.target.value)}
                  name="email"
                  autoComplete="email"
                  aria-describedby="email-error-text"
                />
   </div>);
}

Here you can find source code of this component: https://github.com/przemek-nowicki/auth-react-and-redux/blob/master/src/componnents/Register.js 在这里您可以找到此组件的源代码: https : //github.com/przemek-nowicki/auth-react-and-redux/blob/master/src/componnents/Register.js

You should probably store the error bool in the state as well. 您可能还应该在状态中存储错误布尔值。

 const [emailError, setEmailError] = useState(false); const [email, setEmail] = useState(''); useEffect(() => { setEmailError(!email); }, [email]); 

You can use this, 你可以用这个

const [emailError, setEmailError] = useState(false);
 const [email, setEmail] = useState('');
 const validateEmail = (email) => {
    if(email) {
      setEmailError(false);
    } else {
      setEmailError(true); 
    }
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM