【问题标题】:React Native - useState not updating immediatlyReact Native - useState 不会立即更新
【发布时间】:2022-08-14 17:47:29
【问题描述】:

onLongPress 触发时,我正在尝试更新我的状态。
我在 setState 之后立即打印结果,但它什么也没显示(在第一次按下时) 代码:

const [pressedImagesm setPressedImages] = useState([]);
...
onLongPress={() => {
          setPressedImages(oldArray => [...oldArray, { [index]: true }]);
          console.log(pressedImages);
}}

标签: react-native state


【解决方案1】:

那是因为setPressedImages 不会直接更新状态对象(pressedImages)。相反,它会将此更新添加到队列中,并且更新的状态会反映在组件的下一次渲染中。

这是一个非常常见的 React 问题 - 有很多有用的内容可以更详细地解释它(例如 this articlethis SO question)。

【讨论】:

    【解决方案2】:

    尝试这个:

    const [pressedImages, setPressedImages] = useState([]);
    ...
    onLongPress={() => {
       const cloneArray = [...pressedImages];
       cloneArray.push({ [index]: true });
       setPressedImages(cloneArray);
    }}
    
    console.log('Updated pressedImages:', pressedImages);

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2022-07-19
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多