简体   繁体   English

如何在 React-Native 的 onPress Alert 函数中设置状态

[英]How to setState inside an onPress Alert function in React-Native

I'm currently playing with ways to change state within an onPress event in React-Native and haven't had much luck.我目前正在尝试在 React-Native 的 onPress 事件中更改状态的方法,但运气不佳。 When somebody presses the "Change State?"当有人按下“更改状态?” option in the summoned alert, I would want to change the state to true .召唤警报中的选项,我想将状态更改为true However, when calling setState() or a useCallback() which toggles the state, it continues to print false printed (twice).但是,当调用setState()或用于切换状态的useCallback() ,它会继续打印false打印(两次)。

FYI: I call the alert as ExampleAlert() rather than <ExampleAlert /> elsewhere in my code.仅供参考:我在代码中的其他地方将警报称为ExampleAlert()而不是<ExampleAlert />

Does this issue have something to do with the way the Alerts are written in RN, or the fact that Alerts do not trigger a re-render?这个问题是否与警报在 RN 中的编写方式有关,或者与警报不会触发重新渲染的事实有关?

  const [state, setState] = useState(false);

  const changeStateCallback = useCallback(() => {
    setState(!state);
  }, [state]);

  const ExampleAlert = () => {
    Alert.alert(
      'Title',
      'Message',
      [
        {
          text: 'Change State?',
          onPress: () => {
            changeStateCallback;
            console.log(state);
            setState(true);
            console.log(state);
          },
        },
        {
          text: 'OK',
          onPress: () => {},
        },
      ],
    );
    return null;
  };

useState is async, you can not see the change in the same enviroment useState 是异步的,在同一个环境下是看不到变化的

so you just need do this:所以你只需要这样做:

onPress: () => {
            setState(true);
          },

or或者

const handlePress =()=>{
 setState(true);
}

    onPress: () => { handlePress },

this syntax () => { } does not execute yet, it's executed when the user clicked over that.这个语法() => { }还没有执行,当用户点击它时它会执行。

edit 1:编辑1:

const handlePress =()=>{
 setState(true);
 console.log(state) // here you can not see the change
}

console.log(state) //put your console outside of handlePress to see the change

I think I know your problem.我想我知道你的问题。

console.log() is a synchronous function, setState() is an async one, called async code won't run until all what's in the current call stack finishes running. console.log()是一个同步函数, setState()是一个异步函数,在当前调用堆栈中的所有内容完成运行之前,称为异步代码不会运行。

You won't see changes in state until later on.直到稍后您才会看到状态的变化。

Have you tried visualizing state with debugging tools?您是否尝试过使用调试工具可视化状态?

Similar question: Console.log() after setState() doesn't return the updated state类似问题: setState() 之后的 Console.log() 不返回更新的状态

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

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