React 第一次没有生成帐号状态,因为它是 null

问题描述 投票:0回答:1

帐号是

userData
的一部分,我将
userData
显示在另一个组件中。它完美地生成了帐号,但不是第一次,因为它设置为
null

我尝试使用

useEffect
,但它只是为每个创建生成相同的数字

function CreateAccount() {
  // Define state variables to manage user input``
  const [fullName, setFullName] = useState("");
  const [balance, setBalance] = useState(null);
  const [gender, setGender] = useState("");
  const [address, setAddress] = useState("");
  const [accountNumber, setAccountNumber] = useState(null);

  // Get the setUserData function from the RegisterContext
  const { setUserData } = useContext(RegisterContext);

  // Function to handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();

    // Generate account number
    const generatedAccountNumber = Math.floor(Math.random() * 1000000000);

    // Gather user input data including the generated account number
    const userData = {
      fullName,
      balance,
      gender,
      address,
      accountNumber
    };

    // Update the userData state in the context provider
    setUserData(userData);

    // Set the accountNumber state once
    setAccountNumber(generatedAccountNumber);
 
javascript reactjs react-hooks
1个回答
0
投票

如果您在

Math.floor(Math.random() * 1000000000)
钩子
useState
 中调用 
const [accountNumber, setAccountNumber] = useState(null);

,您的问题就会得到解决

这将每次用随机的“帐号”初始化状态。

我稍微修改了你的代码以初始化安装上的

accountNumber
状态

// suggestion to move this function yo maybe utils.js or something 
function generateAccountId() {
    return Math.floor(Math.random() * 1000000000);
  };
 

function CreateAccount() {
  // Define state variables to manage user input``
  const [fullName, setFullName] = useState("");
  const [balance, setBalance] = useState(null);
  const [gender, setGender] = useState("");
  const [address, setAddress] = useState("");
  // When the component is mounted we generate an account ID
  const [accountNumber, setAccountNumber] = useState(generateAccountId);

  // Get the setUserData function from the RegisterContext
  const { setUserData } = useContext(RegisterContext);

  // Function to handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();

    // Gather user input data including the generated account number
    const userData = {
      fullName,
      balance,
      gender,
      address,
      accountNumber
    };

    // Update the userData state in the context provider
    setUserData(userData);
}

After this modification, every time your component mounts the `accountNumber` will be generated for you in the `useState` hook. You can init `useState` with a function which is the approach I used. 
© www.soinside.com 2019 - 2024. All rights reserved.