React native 等待useState设置值​;然后调用函数

React native 等待useState设置值​;然后调用函数,react-native,React Native,我使用的是react native而不是expo,当尝试使用UseState设置值时,它不会立即设置,并且我无法获取值​​在另一个功能中 const [gridData, setGridData] = useState([]); useEffect(() => { getGridApi().then((response)=>{ setGridData(response); pressed('Mon', 0);

我使用的是react native而不是expo,当尝试使用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不提供useState回调功能

例如:

从“带回调的使用状态”导入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>
  );
};
const-App=()=>{
const[count,setCount]=useStateWithCallback(0,count=>{
如果(计数>1){
console.log('已达到超过1的阈值');
}否则{
log('未达到阈值');
}
});
返回(
{count}

设置计数(计数+1)}> 增加 ); };
您可以使用,也可以使用自己的自定义挂钩。不幸的是,react不提供useState回调功能

例如:

从“带回调的使用状态”导入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>
  );
};
const-App=()=>{
const[count,setCount]=useStateWithCallback(0,count=>{
如果(计数>1){
console.log('已达到超过1的阈值');
}否则{
log('未达到阈值');
}
});
返回(
{count}

设置计数(计数+1)}> 增加 ); };
Cioa,不幸的是,对于钩子,设置状态是异步的,您无法通过这种方式获取最后一个值。但是您可以使用另一个
useffect
hook来检索状态变量的任何更改

试试这个:

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

但请注意:每次
gridData
更改其值时,都会触发此
useffect
I worte

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

试试这个:

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

但请注意:每次
gridData
更改其值时,都会触发此
useffect
I worte

参考,你可以使用另一个useEffect。参考,你可以使用另一个useEffect。嗯,我不知道这个软件包。有趣的解决方案。你在代码中使用它吗?好吧,明天在工作中,我必须对几个项目进行一些修改…:)谢谢,我同意:)你觉得@Leo怎么样?呃,我不知道这个包裹。有趣的解决方案。你在代码中使用它吗?好吧,明天在工作中,我必须对几个项目进行一些修改…:)谢谢,我同意:)你认为利奥怎么样?