简体   繁体   中英

Alert is empty when the value is present in the input [React.js]

I'm trying to alert with the text box value. In the below code, It'll alert whatever the value is in the input.

import { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  function handle() {
    alert(value);
  }

  return (
    <div className="App">
      <h1>Hello App</h1>
      <input
        type="text"
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
      <button onClick={handle}>Hello</button>
    </div>
  );
}

在此处输入图像描述

But if there is a text value already set from the varialbe, It's not showing the value in the alert box. It's empty. As you can see in the below code. I'm setting a const hello with a string and setting it as value for the input. But it's not showing in the popup.

import { useState } from "react";

export default function App() {
  const [value, setValue] = useState("");

  function handle() {
    alert(value);
  }
  return (
    <div className="App">
      <h1>Hello App</h1>
      <input
        type="text"
        onChange={(e) => {
          setValue(e.target.value);
        }}
        value={"hello"}
      />
      <button onClick={handle}>Hello</button>
    </div>
  );
}

在此处输入图像描述

The reason why the alert doesn't display the "correct" state value is because on handle() the value has not change "on time".

Try this

import { useState, useCallback } from "react";

export default function App() {
  const [value, setValue] = useState("");

  const handle = useCallback(() => {
    alert(value);
  }, [value]);

  return (
    <div className="App">
      <h1>Hello App</h1>
      <input
        type="text"
        value={value}
        onChange={(e) => {
          setValue(e.target.value);
        }}
      />
      <button onClick={handle}>Hello</button>
    </div>
  );
}

Why useCallback() ?

As per React docs . This hook memoise its internal values, and will only update them when any of the dependancies changes.

The value inside the handle() function scope is not updated, by wrapping the handle function inside a useCallback hook and attaching the value state as a dependency you ensure that handle always updates its internal scoped values/variables, hope that helps.

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