按钮工作正常,但仅在第二次单击时

Button working correctly ,but only on second click

import { Input, Box, Text, Divider, Button } from '@chakra-ui/react';
import { useState } from 'react';

export default function SearchGithub() {
  const [username, setUsername] = useState('');
  const [data, setData] = useState({});

  async function handleGithubSearch() {
    await fetch('/api/github', {
      method: 'POST',
      body: JSON.stringify(username),
    })
      .then((response) => response.json())
      .then((data) => setData(data));
    console.log(data);
  }

  function handleUsername(e) {
    setUsername(e.target.value);
  }

  return (
    <Box>
      <Text fontSize="lg"> Search for Github Repositories!</Text>
      <Divider />
      <Input
        placeholder="Enter a github username"
        onChange={handleUsername}
        value={username}
      />
      <Button
        colorScheme="telegram"
        position="fixed"
        ml="3px"
        onClick={handleGithubSearch}
      >
        Submit
      </Button>

      {data ? <h1> {data.login}</h1> : null}
    </Box>
  );
}

嘿,我正在尝试制作这个 github 搜索应用程序。每当我单击提交用户名并带回数据时,该功能直到第二次单击才会触发。我很好奇为什么。

正如安迪所说,你不能在设置后记录状态,但你可以使用效果钩子来做。每 the documentation:

Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component. Instead, use useEffect. The function passed to useEffect will run after the render is committed to the screen. By default, effects run after every completed render, but you can choose to fire them only when certain values have changed.

你的函数

 async function handleGithubSearch() {
    await fetch('/api/github', {
      method: 'POST',
      body: JSON.stringify(username),
    })
      .then((response) => response.json())
      .then((data) => setData(data));
    console.log(data);
  }

是异步函数,也就是说它在执行期间需要等待 所以在你的按钮上你需要等待这个承诺完成以及下面是我会怎么做

 <Button
    colorScheme="telegram"
    position="fixed"
    ml="3px"
    onClick={async () => { 
                await handleGithubSearch() 
             }}
  >
    Submit
  </Button>