最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hooks State update one step behind. For this reason my changes are not working correctly - Stack Overflow

programmeradmin0浏览0评论

I want to see the changes in the use of react hooks on state immediately. My changes are one step behind on state. How can I solve this.

const [categoryID, setCategoryID] = useState(0);

const changeCategory = (e) => {
    setCategoryID(e.target.value);
    console.log(categoryID);
  };

<Field
     as="select"
     onChange={changeCategory}
     style={formStyle().inputStyle}
     className="form-control"
     type="text"
     name="categoryID"
      >

When I select the first value, the result appears 0. If I chose my second value, I see the value I chose first on the console.

I want to see the changes in the use of react hooks on state immediately. My changes are one step behind on state. How can I solve this.

const [categoryID, setCategoryID] = useState(0);

const changeCategory = (e) => {
    setCategoryID(e.target.value);
    console.log(categoryID);
  };

<Field
     as="select"
     onChange={changeCategory}
     style={formStyle().inputStyle}
     className="form-control"
     type="text"
     name="categoryID"
      >

When I select the first value, the result appears 0. If I chose my second value, I see the value I chose first on the console.

Share Improve this question edited Sep 15, 2020 at 16:22 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Sep 14, 2020 at 13:52 GucalGucal 9311 gold badge12 silver badges22 bronze badges 1
  • 1 So categoryID will be updated on the next render. You already know what value it will be updated to, so while you wait for it, you can log console.log(e.target.value). – spender Commented Sep 14, 2020 at 14:01
Add a ment  | 

2 Answers 2

Reset to default 2

State change is asynchronous in react hooks hence there is no guarantee that the state will be updated just after setting it. For this reason we have useEffect to the rescue that accepts a dependency and will be executed after that dependency is changed.

Example-

useEffect(() => {
  console.log(categoryID);
},[categoryID])

Now in this case the dependency is categoryID and whenever it's value is changed the function will be executed and will console the updated value.

The main reason behind this behavior is setState is asynchronous so the changes should not be expected immediately.

Specially for this cases there is a hook called useEffect() to capture changes on state. If you add categoryId into the dependency array of useEffect then it will be trigger once you have change on that state. Thus you can log your changes as the following:

useEffect(() => {
   console.log('changed', categoryID);
}, [categoryID]);

Suggested read is Using the Effect Hook.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论