【问题标题】:wait for useState to set values ​and then call function等待 useState 设置值然后调用函数
【发布时间】:2020-11-29 06:57:01
【问题描述】:

我正在使用没有expo的react native,尝试使用UseState设置值时它不会立即设置,并且我无法在另一个函数中获取值。

const [gridData, setGridData] = useState([]);

useEffect(() => {
        getGridApi().then((response)=>{
            setGridData(response);
            pressed('Mon', 0);
        })
    
}, []);

const pressed = async (category, index) => {
    console.log(gridData); // empty
}

如何让它等待设置然后调用函数pressed()

【问题讨论】:

标签: react-native


【解决方案1】:

您可以使用this package 或您自己的自定义挂钩。不幸的是,react 没有提供 useState 和回调功能

例子:

从'use-state-with-callback'导入useStateWithCallback;

const App = () => {
  const [count, setCount] = useStateWithCallback(0, count => {
    if (count > 1) {
      console.log('Threshold of over 1 reached.');
    } else {
      console.log('No threshold reached.');
    }
  });
 
  return (
    <div>
      <p>{count}</p>
 
      <button type="button" onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
};

【讨论】:

  • 呃,我不知道这个包。有趣的解决方案。你在你的代码中使用它?
  • 好吧好吧,明天上班我要对几个项目做一些修改... :) 谢谢
  • 是的,我同意 :) @Leo 你怎么看?
【解决方案2】:

Cioa,不幸的是,使用钩子,设置状态是异步的,您无法以这种方式获取最后一个值。但是您可以使用另一个 useEffect 挂钩来检索状态变量的任何更改。

试试这个:

useEffect(() => {
   console.log(gridData);  // this shows the last value of gridData setted by the other useEffect
}, [gridData]);

但是注意:这个useEffect我写的每次gridData改变他的值都会触发!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-06
    • 2018-08-03
    • 2020-12-16
    • 2020-12-17
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多