简体   繁体   中英

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.

I am building a simple registration form with Material UI and React 16.8. It comes with the hooks API that I am trying to use. 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

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); 
    }
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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