简体   繁体   English

React usestate 在第一次单击或第一次时未更新

[英]React usestate not updating on first Click Or on First time

Please, See this - https://codesandbox.io/s/morning-grass-z8qrq请看这个 - https://codesandbox.io/s/morning-grass-z8qrq

https://codesandbox.io/s/blue-flower-wl92u https://codesandbox.io/s/blue-flower-wl92u

** the second click, third, fourth, fifth click - menuOpen is true, then again click false - behaves as expected** ** 第二次单击、第三次、第四次、第五次单击 - menuOpen 为 true,然后再次单击 false - 行为与预期一样**

let [menuOpen, setMenuOpen] = useState(false);

<div
    onClick={() => {
    // setMenuOpen(true);

    setMenuOpen(!menuOpen); // I's not updated in the First time.

    console.log(menuOpen); // First time: false // not updating
>
 .......// some code
</div>

Please give me, some answers.请给我一些答案。 I have been trying to solve this problem for Two days.这两天我一直在尝试解决这个问题。 I just can't solve it.我就是无法解决。

Try this:尝试这个:

export default function App() {
  const [menuOpen, setMenuOpen] = useState(false);
  return (
    <>
      <button onClick={() => setMenuOpen(!menuOpen)}>Click</button>
      Is menu Open: { menuOpen ? "True": "False"}
    </>
  );
}

Example demo can be found here .示例演示可以在这里找到。

useState create queues for React core to update the state object of a React component. useState 为 React 核心创建队列以更新 React 组件的 state object。 So the process to update React state is asynchronous for performance reasons.因此,出于性能原因,更新 React state 的过程是异步的。 That's why changes don't feel immediate.这就是为什么变化不会立竿见影。

Give this a try试试这个

setMenuOpen(prevMenuOpenState => !prevMenuOpenState);

or或者

<div
    onClick={() => setMenuOpen(!menuOpen)}
>

The Answer is just refactoring the code into class Component without using hooks useState.答案只是将代码重构为 class 组件,而不使用钩子 useState。 Using state and setState to update.使用 state 和 setState 进行更新。 The Problem will solve.问题会解决。

But If I use useState hooks the problem remains the same Whatever I do with the code.但是如果我使用 useState 钩子,无论我对代码做什么,问题仍然是一样的。

I had even this problem in my code.我的代码中什至有这个问题。 My scenario is as follows: Its hotel detail page.我的场景如下:它的酒店详情页面。 There is horizontal tab menu of room types.有房间类型的水平标签菜单。 If a hotel has more than 3 types of room, then there is show room button.如果酒店有超过 3 种类型的房间,则有显示房间按钮。 I am using React Functional components in through the code.我正在通过代码使用 React 功能组件。 hotel detail basic page and room section page are different components created.酒店详情基本页面和房间部分页面是创建的不同组件。 values are passed to room section components through props.值通过道具传递给房间部分组件。

My problem: When I click to room type further 3rd type, then show room value in function (setSelectedTab()) room component doesn't set at an instant.我的问题:当我单击房间类型进一步第 3 种类型时,然后在 function (setSelectedTab()) 房间组件中显示房间值不会立即设置。 And hence as function moves further, it doesn't set document.getElementById(id) since show room had not been set.因此,随着 function 进一步移动,它不会设置 document.getElementById(id),因为尚未设置展厅。 As function (setSelectedTab()) completes in first click it sets the show room to true, but selected tab doesn't set.由于 function (setSelectedTab()) 在第一次单击时完成,它将展示室设置为 true,但未设置选定的选项卡。 I had to click 2nd time to set the tab.我不得不点击第二次来设置标签。

solution: After a long try and error, I settle down to the following: I declare the function as async and made await the setshowRoom() value.解决方案:经过长时间的尝试和错误,我解决了以下问题:我将 function 声明为异步并等待 setshowRoom() 值。 This solved my complete problem.这解决了我的完整问题。

async function setSelectedTab(e, data) {
firstScroll += 1;

data >= 2 && await setMenuOpen(true);
if (data >= 0) {
  .................
  const id = e.href;
  const anchor = document.getElementById(id);
  ..............
..............
}
}

and in room component: showRoom, setshowRoom in useState and calling the setSelectedTab() using props.在房间组件中:showRoom、setshowRoom 在 useState 并使用道具调用 setSelectedTab()。 This solves problem of single click这解决了单击的问题

Drawback: I found delay of 1 second to set this tab.缺点:我发现设置此选项卡的延迟时间为 1 秒。

If anyone have better solution than this without making async await, then please post here.如果有人在不进行异步等待的情况下有比这更好的解决方案,请在此处发布。 Thanks.谢谢。

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

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