动态路由未定义

Dynamic routing getting undefined

我正在使用的 API 从用户接收一个 phone 数字作为 return 数据的参数。所以在 UI 中,我收到了这个数字,通过 console.log 我可以看到数据。但我也想,当点击按钮时,用户会被带到一个 link 只包含与他们相关的数据,为此我相信我必须将用户重定向到一个动态 link 例如:' /user/john'。我总是在 link 中得到 undefined,但我不知道为什么。感觉状态本身并没有存储 API 数据

const Login =()=> {
  const history = useHistory()
  const location = useLocation()
  const [state, setState] = useState('')
  const [data, setData] = useState({});
  const phone = state
...
  let headers = new Headers();
  headers.set("Authorization", "Basic " + btoa(username + ":" + password));

    const handleClick=() => {
    getData();
  };    
  
  const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    setData(response.user[0].attributes[0]);
    history.push(`/user/${data.name}`)
  };
  
   const onTextChange = event => {
        setState(event.target.value);
      }
<input onChange={onTextChange}>
 <Button  onClick={handleClick} >
    login
 </Button> 

State 始终异步设置 (more details)。 setData(response.user[0].attributes[0]) 需要一些,因为 js 是异步的,下一行将被执行,即 history.push('/user/${data.name}')。由于还没有数据,所以 data.name 将是未定义的。

您必须直接使用 history.push(/user/${(response.user[0].attributes[0]).name})

这是更新后的代码:

    const Login = () => {
    const history = useHistory()
    const location = useLocation()
    const [state, setState] = useState('')
    const [data, setData] = useState({});
    const phone = state
    ...
    let headers = new Headers();
    headers.set("Authorization", "Basic " + btoa(username + ":" + password));

    const handleClick = () => {
    getData();
    };

    const getData = async () => {
    const a = await fetch(url, { method: "GET", headers: headers });
    const response = await a.json();
    const respData = response.user[0].attributes[0]
    setData(respData);
    history.push(`/user/${respData.name}`)
    };

    const onTextChange = event => {
    setState(event.target.value);
    }
    <input onChange={onTextChange}>
    <Button onClick={handleClick} >
      login
    </Button>