React Native-提取到setState返回旧值

时间:2020-10-27 22:35:31

标签: react-native react-hooks setstate

单击按钮(取消或完成)时,我尝试使用API​​请求Post更新数据库中的行。

该值已在数据库中正确更新,但是当我单击onPress={() => { settersApi('Finish'); gettersApi(); }} gettersApi()中的按钮console.log(estado)时,从钩子“ estado”返回了旧值。

export default Home = ({navigation}) => {
  const [estado, setEstado] = useState([]);

  const gettersApi = async () => {
    try {
      let response = await fetch(
        'http://api/getValues', {
          headers: {
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache'
          },
        }
      );
      let json = await response.json();
      setEstado(json);
      console.log(estado);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    gettersApi();
  }, []);


const settersApi = async (param) => {
  try {
    let response = await fetch(
      'http://api/setValues', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache'
        },
        body: JSON.stringify({
          id: estado.id,
          estado: param,
        })
      }
    );
    let json = await response.json();
  } catch (error) {
    console.error(error);
  }
};

  
  const CButtons = () => {
   
      return (
        <View>
          <View> 
            <Button
            color='#ffc107'
            title="CANCEL"
            onPress={() => {
              settersApi('Cancel');
              gettersApi();
            }}
            />

            </View>
            <View> 
            <Button
            color='#28a745'
            title="FINISH"
            onPress={() => {
              settersApi('Finish');
              gettersApi();
            }}
            />
            </View>
          </View>
      );
    
  };


  return (
    <View style={styles.body}>
      <CButtons></CButtons>
    </View>
  );
};

1 个答案:

答案 0 :(得分:0)

您从@media screen and (max-width: 1140px) { .wrapper { display: block; overflow: auto; } .insider_company_table { display: flex; } .insider_company_table thead, tbody { display: grid; } .insider_company_table thead tr, tbody tr { display: grid; grid-auto-rows: 1fr; } ... } 调用的函数useState是异步函数。更改后,您将不会立即看到任何更改。

尝试查看变量状态,并使用setEtado

查看其更新时间
useEffect
相关问题