简体   繁体   English

在 React Hooks on Change 方法中更新 State

[英]Update State in React Hooks on Change method

I am wondering why React is not updating the state after a method onChange is called.我想知道为什么 React 在调用onChange方法后不更新 state。

Summary: A simple input element with two float-right icons to display.简介:一个简单的输入元素,带有两个要显示的右浮动图标。 One icon to display if the length of the input text is 0 while the other if the input text length > 0. But it seems React is updating the state after I enter the second text in my input element.如果输入文本的长度为 0,则显示一个图标;如果输入文本长度 > 0,则显示另一个图标。但在我在输入元素中输入第二个文本后,React 似乎正在更新 state。

What I need is:我需要的是:

Display % if length == 0 and display X is length is > 0.如果长度 == 0 则显示%并且显示X是长度 > 0。

And if the length > 0 then user on click of X set the input text == "" OR input.length = 0.如果长度 > 0,则用户点击X设置输入文本 == "" 或 input.length = 0。

Problem is: Though I am able to clear the input but the icon % is not displayed.问题是:虽然我能够清除输入,但未显示图标%

  const onChange = (e: any) => {
    //setting user input
    if (userInput.length > 0)
      setDisplayIcon({ default: "d-none", clear: "d-block" });
    else setDisplayIcon({ default: "d-block", clear: "d-none" });
  };

  const clearText = (e: any) => {
    setUserInput("");
  };

  return (
   
            <label id="default" className={`${displayIcons.default}`}>
              %
            </label>
            <label className={`${displayIcons.clear}`} onClick={clearText}>
              X
            </label>
  );
}

Add setting display icon state:添加设置显示图标 state:

const clearText = (e: any) => {
    setUserInput("");
    setDisplayIcon({ default: "d-block", clear: "d-none" });
};

You will not be able to console.log the updated state value inside of the same function. Try placing your console.log outside of the function and you will see that it does in fact update.您将无法在同一个 function 内使用 console.log 更新 state 值。尝试将您的 console.log 放在 function 之外,您会发现它确实更新了。

"setState is asynchronous call means if synchronous call get called it may not get updated at right time like to know current value of object after update using setState it may not get give current updated value on console. To get some behavior of synchronous need to pass function instead of object to setState." “setState 是异步调用意味着如果同步调用被调用,它可能不会在正确的时间得到更新,比如在使用 setState 更新后知道 object 的当前值,它可能无法在控制台上给出当前更新值。要获得一些同步行为需要通过function 而不是 object 到 setState。” - https://www.geeksforgeeks.org/reactjs-setstate/ - https://www.geeksforgeeks.org/reactjs-setstate/

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

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