【问题标题】:Dynamic routing getting undefined动态路由变得未定义
【发布时间】:2020-11-19 21:56:43
【问题描述】:

我使用的 API 接收电话号码作为参数以从用户返回数据。所以在 UI 中,我收到了这个号码,通过console.log 我可以看到数据。但我也希望,当点击按钮时,用户会被带到一个只包含与他们相关的数据的链接,为此我相信我必须将用户重定向到一个动态链接,例如:'/user/john'。我总是在链接中收到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> 

【问题讨论】:

    标签: reactjs react-router setstate use-state


    【解决方案1】:

    状态总是异步设置 (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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 2023-03-19
      • 2015-11-09
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多