【问题标题】:There is a problem with getting API using useEffect使用 useEffect 获取 API 时出现问题
【发布时间】:2022-11-02 19:57:25
【问题描述】:

我现在正在处理 API 链接。我编写了一个代码,通过在第一次渲染组件并且userName 的值发生变化时重新渲染来接收 API 值。但是,出现错误“Uncaught TypeError:destroy is not a function”并且该值没有进入控制台。我想我写了错误的代码,但我应该怎么做才能将值输入控制台?此外,它在其他地方声明过,但只要通过onChange 输入值,userName 就会通过setUserName 更改。如果您让我知道,我将不胜感激谢谢!

用户.jsx:

import React, { useEffect, useState } from 'react'
import styled from 'styled-components';
import axios from 'axios';

const InputWrap = styled.div`
  align-items: center;
  -webkit-appearance: none;
  background: rgb(250, 250, 250);
  border: 1px solid rgb(219, 219, 219);
  border-radius: 3px;
  box-sizing: border-box;
  color: rgb(38, 38, 38);
  display: flex;
  flex-direction: row;
  font-size: 14px;
  position: relative;
  width: 100%;
`

function SignUpUserInput({userName,setUserName}) {
useEffect (async()=> {
    try{
      const userData = await axios({
        method : 'get',
        url : `https://cors-anywher.herokuapp.com/https://clone-instagram.shop:8080/users/checkid?id=${userName}`
      })

      console.log(userData);
    }

    catch(error) {
      alert(error);
    }
},[userName])

  return (
    <InputWrap>
      <label className='inputLabel'>
        <span className='inputHover'>
          name
        </span>
        <input className='inputInput' value={userName} onChange={(e)=>{setUserName(e.target.value)}}/>
      </label>
    </InputWrap>
  )
}

export default SignUpUserInput;

固定的

useEffect (()=> {
  async function fetchData () {
    try{
      const userData = await axios({
        method : 'get',
        url : `https://cors-anywher.herokuapp.com/https://clone-instagram.shop:8080/users/checkid?id=${userName}`
      });

      console.log(userData);
    }

    catch(error) {
      alert(error);
    }
  }
  fetchData();
},[])

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    useEffect()回调函数不应该是async

    useEffect(() => {
        // declare a async func
        async function fetchData() {
          try {
            const userData = await axios({
              method: "get",
              url: `https://cors-anywher.herokuapp.com/https://clone-instagram.shop:8080/users/checkid?id=${userName}`,
            });
    
            console.log(userData);
          } catch (error) {
            alert(error);
          }
        }
        fetchData();
      }, []);
    

    【讨论】:

    • 感谢你的回复。即使我按照您所说的进行了更正,仍然会发生相同的错误。我已经提交了修改后的代码!
    • url 格式不正确。
    • 我知道了。现在它工作得很好。太感谢了!!!!!!!
    猜你喜欢
    • 2020-09-16
    • 2021-10-07
    • 2020-01-30
    • 2022-01-22
    • 2020-09-10
    • 2018-07-17
    • 2020-08-22
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多