首页 > 解决方案 > 使用钩子时等待状态更新

问题描述

如何使用 Hooks 等待状态更新。当我提交表单时,我需要termsValidation在运行一些附加代码之前检查是否为假。如果状态刚刚改变,它就不会注意到这一点。

import React, { useState } from 'react';

export default function Signup() {
  const [terms, setTerms] = useState('');
  const [termsValidation, setTermsValidation] = useState(false);

  function handleSubmit(e) {
    e.preventDefault();

    if (!terms) {
      setTermsValidation(true);
    } else {
      setTermsValidation(false);
    }

    if (!termsValidation) {
      console.log('run something here');
    }
  }

  return (
    <div>
      <form>
        <input type="checkbox" id="terms" name="terms" checked={terms} />

        <button type="submit" onClick={handleSubmit}>
          Sign up
        </button>
      </form>
    </div>
  );
}

标签: reactjs

解决方案


钩子是异步的useState,但它没有回调 api setState。如果你想等待状态更新,你需要一个useEffect钩子:

import React, { useState, useEffect } from 'react';

export default function Signup() {
  const [terms, setTerms] = useState('');
  const [termsValidation, setTermsValidation] = useState(false);

  useEffect(() => {
    if (!termsValidation) {
      console.log('run something here');
    }
  }, [termsValidation]);

  function handleSubmit(e) {
    e.preventDefault();

    if (!terms) {
      setTermsValidation(true);
    } else {
      setTermsValidation(false);
    }
  }

  return (
    <div>
      <form>
        <input type="checkbox" id="terms" name="terms" checked={terms} />

        <button type="submit" onClick={handleSubmit}>
          Sign up
        </button>
      </form>
    </div>
  );
}

推荐阅读