React useState总是落后1步 [英] React useState is always behind 1 step

查看:131
本文介绍了React useState总是落后1步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React很陌生.我已经学习了几个月了.我目前正在使用ant-design创建代码,并试图在点击时将其删除.我有一个用户状态,并且根据他们是否要删除或创建标签来更新用户状态.但是,当我删除标签时, users 状态不会立即更新,并且当我 console.log(users); removeUser().我之前看过类似的问题,但是它们利用了 useEffect(),但这不适用于我的用例.我还尝试将< Tag> 放入代码的返回部分,这可以解决问题,但是每次我从的表格中选中一个复选框时,标记的颜色都会不断重新呈现.用户.删除标记后,将调用 removeUser()函数,该函数在哪里解析userId,以便可以从状态中删除用户.但是,由于状态未更新,因为状态为空,所以不会将其删除,因此 [... users] .map()不会映射任何内容.我该如何解决?

I'm quite new to React. I have been learning this for a couple of months. I'm currently creating tags using ant-design and trying to removing them on click. I have a state of users and depending on whether they want to remove or create a tag the user state is updated. However, when the I remove the tag the users state doesn't update immediately and returns empty array when I console.log(users); in the removeUser() . I have looked a previous questions similar to this however they utilise useEffect() but this not suitable for my use case. I have also tried putting this <Tag> in the return part of the code which sort of solves the problem however the colour of the tags keeps re-rendering every time I check a checkbox from the table of users. When the tag is removed the removeUser() function is called where is parse the userId so I can remove the user from the state. However, because the state isn't updated it won't remove it since it's empty so the [...users].map() doesn't map through anything. How do I resolve this?


const [users, setUsers] = useState([]);

const createUserTags = () => {
  const oldUsers = [...users];
  let updatedUsers = selectedRowKeys.map(userId => ( 
  <Tag onClose = {() => removeUser(userId)}
    closable key = {userId}> 
    {[...dataSource].map(user => {
    return user.Id === userId && "{user.firstName}" + " "+"{user.surname}";
      })
    } 
  </Tag>
  ));
  updatedUsers.unshift(oldUsers);
  setUsers([...updatedUsers]);
};

  const removeUser = userId => {
   
        // remove user from array list
       
   };


return (
  <>
    <Button 
      shape = "round"
      onClick = {() => createUserTagsHandler()}
      type = "primary"> Create Tag 
    </Button> 
</>
  </>
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

推荐答案

setState 操作是异步的,并且为了提高性能而进行了批量处理.在 setState

setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState

setState()不会立即使this.state突变,而是创建一个挂起的状态转换.调用此方法后访问this.state可能会返回现有值.无法保证对setState调用的同步操作,并且可能会批量调用以提高性能.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

如果需要确保在进行setState调用后事件的顺序,则可以传递一个回调函数. this.setState({something:true},()=> console.log(this.state))

If you need to ensure ordering of events after a setState call is made, you can pass a callback function. this.setState({ something: true }, () => console.log(this.state))

这篇关于React useState总是落后1步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆