React-如何获取异步函数之外的数据?

我正在尝试在fetchUserData()函数之外获取“ body”的数据。 我只想将其存储在变量中以备后用。 也尝试修改状态,但也没有用。 感谢您的帮助:)

const [userData,setUserData] = useState();

  async function fetchUserData () {
    try {
    const result = await fetch(`/usermanagement/getdocent`,{
      method: "GET"
    });
    const body = await result.json();
    //setUserData(body);
    return(
      body
    )
    } catch (err) {
      console.log(err);
    }
  }

  let userTestData
  fetchUserData().then(data => {userTestData = data});
  console.log(userTestData);
  //console.log(userData);
youlan01 回答:React-如何获取异步函数之外的数据?

使用useEffect

async function fetchUserData () {
  try {
    const result = await fetch(`/usermanagement/getdocent`,{
      method: "GET"
    })

    return await result.json()
  } catch (err) {
    console.log(err)
    return null
  }
}

const FunctionalComponent = () => {
  const [userData,setUserData] = useState()

  useEffect(() => {
    fetchUserData().then(data => {
      data && setUserData(data)
    })
  },[]) // componentDidMount

  return <div />
}

Ben Awad's awesome tutorial

示例:

Edit relaxed-khorana-ctn39

,

看来您使它变得比应有的复杂。当您获得响应(即带有异步函数中数据的已解决承诺)时,只需设置状态,然后在下一个渲染中就应获取更新的数据。

示例

const [userData,setUserData] = useState();

useEffect(() => {
 const getResponse = async () => {
  try {
   const result = await fetch(`/usermanagement/getdocent`,{
    method: "GET"
   });
   const body = await result.json();
   setUserData(body);
  } catch (err) {
   console.log(err)
  }
 }

 getResponse();
},[])

console.log(userData);
return <div></div>

假设您只需要调用一次函数定义,然后在useEffect或'componentDidMount'中调用它。为了在useEffect中使用异步函数,我们需要定义另一个函数,然后调用它。

,

这样做的时候

let userTestData

// This line does not wait and next line is executed immediately before userTestData is set
fetchUserData().then(data => {userTestData = data}); 

console.log(userTestData);

// Try changing to 
async someAsyncScope() {
  const userTestData = await fetchUserData();
  console.log(userTestData)
}

示例:

state = {
  someKey: 'someInitialValue'
};

async myAsyncMethod() {
  const myAsyncValue = await anotherAsyncMethod();
  this.setState({ someKey: myAsyncValue });
}
/*
 * Then in the template or where ever,use a state variable which you update when 
 * the promise resolves. When a state value is used,once the state is updated,* it triggers as a re-render
*/
render() {
  return <div>{this.state.someKey}</div>;
}

在您的示例中,您将使用setUserData代替this.setState,并使用userData代替{this.state.someKey}

本文链接:https://www.f2er.com/3090340.html

大家都在问