对象上的打字稿useState钩子不保存

时间:2020-05-12 21:27:49

标签: javascript reactjs typescript react-hooks use-state

我无法将axios返回到useState挂钩的对象保存。 带有字符串和布尔值的常规钩子非常完美。这不是。 axios调用以正确的格式返回正确的数据。

我得到了以下useState钩子:

  const [user, setUser] = useState<IUser>({} as IUser);

我正在从我的api中获取数据,然后尝试将其保存到我的钩子中。

  const getUser = async () => {
    const { data } = await axios.get('me'); // this holds the correct data {id:1,...}
    setUser(data);
    console.log(user); // setting this return nothing
  }

3 个答案:

答案 0 :(得分:2)

TL; DR: react中的状态更新是异步的。


setUser在调用时不会直接更新userreact将更新user,但不会告诉您确切的时间。更新的值很可能在下一个渲染中可用。

如果您想对await进行状态更新,那么大多数时候就足以使用useEffect

useEffect(() => console.log(user), [user])

我还写了一个关于该主题的blog post,对它进行了深入研究。

答案 1 :(得分:1)

您的代码运行正常,但您将数据记录在错误的位置。 在getUSer方法上,awaitsetUser都是异步api调用,但是console是同步的,这就是为什么在更新之前先对其user进行控制台。 最初user是{},这就是为什么它什么也没给出的原因。

答案 2 :(得分:1)

您可能想考虑一种更通用的方法-

const identity = x => x

const useAsync = (runAsync = identity, deps = []) => {
  const [loading, setLoading] = useState(true)
  const [result, setResult] = useState(null)
  const [error, setError] = useState(null)

  useEffect(_ => { 
    Promise.reolve(runAsync(...deps))
      .then(setResult, setError)
      .finally(_ => setLoading(false))
  }, deps)

  return { loading, result, error }
}

在组件中使用useAsync看起来像这样-

const MyComponent = ({ userId = 0 }) => {
  const { loading, error, result } =
    useAsync(UserApi.getById, [userId])

  if (loading)
    return <pre>loading...</pre>

  if (error)
    return <pre>error: {error.message}</pre>

  return <pre>result: {result}</pre>
}

如果您有许多需要查询用户的组件,则可以相应地专门设置useAsync-

const useUser = (id = 0) =>
  userAsync(UserApi.getById, [id])

const MyComponent = ({ userId = 0 }) => {
  const { loading, error, result:user } =
    useUser(userId)

  if (loading)
    return <pre>loading...</pre>

  if (error)
    return <pre>error: {error.message}</pre>

  return <pre>user: {user}</pre>
}

这是一个代码段,您可以运行该代码段以在自己的浏览器中验证结果-

const { useState, useEffect } =
  React

const identity = x => x

const useAsync = (runAsync = identity, deps = []) => {
  const [loading, setLoading] = useState(true)
  const [result, setResult] = useState(null)
  const [error, setError] = useState(null)

  useEffect(_ => { 
    Promise.resolve(runAsync(...deps))
      .then(setResult, setError)
      .finally(_ => setLoading(false))
  }, deps)

  return { loading, result, error }
}

const _fetch = (url = "") =>
  fetch(url).then(x => new Promise(r => setTimeout(r, 2000, x)))

const UserApi = {
  getById: (id = 0) =>
    id > 500
      ? Promise.reject(Error(`unable to retrieve user: ${id}`))
      : _fetch(`https://httpbin.org/get?userId=${id}`).then(res => res.json())
}
  
const useUser = (userId = 0) =>
  useAsync(UserApi.getById, [userId])

const MyComponent = ({ userId = 0 }) => {
  const { loading, error, result:user } =
    useUser(userId)

  if (loading)
    return <pre>loading...</pre>
  if (error)
    return <pre style={{color:"tomato"}}>error: {error.message}</pre>
  return <pre>result: {JSON.stringify(user, null, 2)}</pre>
}

const MyApp = () =>
  <main>
    <MyComponent userId={123} />
    <MyComponent userId={999} />
  </main>

ReactDOM.render(<MyApp />, document.body)
pre {
  background: ghostwhite;
  padding: 1rem;
  white-space: pre-wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>


真正的自定义

当然,这只是设计useAsync的一种方法。设计自定义挂钩的方式可以极大地改变它们的使用方式-

const MyComponent = ({ userId = 0 }) =>
  useUser(userId, {
    loading: _ => <pre>loading...</pre>,
    error: e => <pre style={{color:"tomato"}}>error: {e.message}</pre>,
    result: user => <pre>result: {JSON.stringify(user, null, 2)}</pre>
  })

这样的自定义钩子可以这样实现-

const identity = x => x

const defaultVariants =
  { loading: identity, error: identity, result: identity }

const useAsync = (runAsync = identity, deps = [], vars = defaultVariants) => {
  const [{ tag, data }, update] =
    useState({ tag: "loading", data: null })

  const setResult = data =>
    update({ tag: "result", data })

  const setError = data =>
    update({ tag: "error", data })

  useEffect(_ => {
    Promise.resolve(runAsync(...deps))
      .then(setResult, setError)
  }, deps)

  return vars[tag](data)
}

并且useUser已更新为通过cata

const useUser = (userId = 0, vars) =>
  useAsync(UserApi.getById, [userId], vars)

通过运行以下代码段验证结果-

const { useState, useEffect } =
  React

const identity = x => x

const defaultVariants =
  { loading: identity, error: identity, result: identity }

const useAsync = (runAsync = identity, deps = [], vars = defaultVariants) => {
  const [{ tag, data }, update] =
    useState({ tag: "loading", data: null })
    
  const setResult = data =>
    update({ tag: "result", data })

  const setError = data =>
    update({ tag: "error", data })

  useEffect(_ => {
    Promise.resolve(runAsync(...deps))
      .then(setResult, setError)
  }, deps)

  return vars[tag](data)
}

const _fetch = (url = "") =>
  fetch(url).then(x => new Promise(r => setTimeout(r, 2000, x)))

const UserApi = {
  getById: (id = 0) =>
    id > 500
      ? Promise.reject(Error(`unable to retrieve user: ${id}`))
      : _fetch(`https://httpbin.org/get?userId=${id}`).then(res => res.json())
}
  
const useUser = (userId = 0, vars) =>
  useAsync(UserApi.getById, [userId], vars)

const MyComponent = ({ userId = 0 }) =>
  useUser(userId, {
    loading: _ => <pre>loading...</pre>,
    error: e => <pre style={{color:"tomato"}}>error: {e.message}</pre>,
    result: user => <pre>result: {JSON.stringify(user, null, 2)}</pre>
  })

const MyApp = () =>
  <main>
    <MyComponent userId={123} />
    <MyComponent userId={999} />
  </main>

ReactDOM.render(<MyApp />, document.body)
pre {
  background: ghostwhite;
  padding: 1rem;
  white-space: pre-wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>