从异步方法分配变量

Assign variable from async method

我使用 AWS-Amplify 并希望从 Cognito 获取所有者并将其分配给变量所有者。当我在 then( 中执行 console.log(user.username) 时,我看到了正确的数据。但是,当我执行 console.log(owner); 时,我只看到 null.

function App() {
  // Get user
  let owner = null;

  Auth.currentAuthenticatedUser({
    bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
  })
    .then(user => {
      owner = user.username;
    })
    .catch(err => console.log(err));

  console.log(owner);
function App() {
  // Get user
  let owner = null;

  return Auth.currentAuthenticatedUser({
    bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
  })
    .then(user => {
      owner = user.username;
      console.log(owner);
      return owner
    })
    .catch(err => console.log(err));

因为 Auth 是异步的 console.log(owner) 在 promise 解析之前执行。移到 then 看结果。

您不想在组件体内产生任何副作用,并且如果您需要保留某种随时间变化的数据,state 就是合适的地方。

对于副作用使用 useEffect 可以配置何时使用 dependencies 数组触发回调函数,在这种情况下该数组为空,并且仅在挂载时触发回调函数

function App() {
  const [owner, setOwner] = useState(null)

  useEffect(() => {
    Auth.currentAuthenticatedUser({
      bypassCache: false,
    })
      .then((user) => {
        setOwner(user.username)
      })
      .catch(console.log)
  }, [])

  return <div>{owner}</div>
}