简体   繁体   English

当我使用 async-await 和 useEffect 时,我应该如何存储获取的数据?

[英]How should I store the fetched data when I'm using async-await and useEffect?

I have to fetch a player's stats based on the input given by the user, and then display it.我必须根据用户提供的输入获取玩家的统计数据,然后显示它。 I am having trouble storing the fetched data, using useEffect hook.我在使用 useEffect 钩子存储获取的数据时遇到问题。 Please suggest if there's a better way.请建议是否有更好的方法。

    import React, { useEffect, useState } from 'react'
import HLTV from 'hltv';

const getPlayer = async ({ name }) => {
    HLTV.getPlayerByName({ name: name })
        .then(res => console.log(res))
}

const Search = () => {

    const [text, setText] = useState('');

    const onChange = (e) => {
    setText(e.target.value);
}

useEffect(() => {
    getPlayer(text)
}, [text])


return (
    <div>
        <form className="form">
            <input type="text"
                name="text" placeholder="Enter user" onChange={onChange} />
            <input type="Submit"
                defaultValue="search"
                className="btn btn-dark btn-block" />
        </form>

    </div>
)

} }

export default Search导出默认搜索

You can store the player using a useState hook, as follows.您可以使用 useState 钩子存储播放器,如下所示。 You also need to bring the getPlayer() function inside the Search function so that you can access the player variable.您还需要在 Search 函数中引入getPlayer()函数,以便您可以访问 player 变量。 Also, when you use an async function , you don't need to use then ;此外,当您使用 async function 时,您不需要使用then you can use await instead.你可以使用await代替。

One last thing to point out: If you're making network calls, you have to account for the possibility that they could fail, so you might want to put the call to getPlayerByName within a try catch.最后要指出的一件事:如果您进行网络调用,则必须考虑它们可能失败的可能性,因此您可能希望将调用getPlayerByName放在 try catch 中。

stackblitz here在这里堆叠闪电战

import React, { useState, useEffect } from "react";
import "./style.css";

const HLTV = {
  getPlayerByName: (name) => {

    return Promise.resolve({
      name: "result:" + name,
    });
  }
};

export const Search = () => {
  const [player, setPlayer] = useState({ name: 'nobody'});

  const [text, setText] = useState("initial text");

  const onChange = e => {
    setText(e.target.value);
  };

  const getPlayer = async (name) => {
    const player = await HLTV.getPlayerByName(name);

    setPlayer(player);
  };

  useEffect(() => {
    getPlayer(text);
  }, [text]);

  return (
    <form className="form">
      <div>text: {text}</div>
      <pre>Player: {JSON.stringify(player, null, 2)}</pre>
      <input
        type="text"
        name="text"
        value={text}
        placeholder="Enter user"
        onChange={onChange}
      />
      <input
        type="Submit"
        defaultValue="search"
        className="btn btn-dark btn-block"
      />
    </form>
  );
};


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在使用async-await语法时我仍然需要等待while循环? - Why I still have to wait for while loop when using async-await syntax? 使用 async-await 时如何将 Resolve 回调传递给 Promise? - How to pass Resolve callback into a Promise when using async-await? 带有 console.log 的 async-await 可以工作,但是当我尝试使用 return 语句时,我得到的是 promise 吗? - async-await with console.log works but when I try to use the return statement I'm getting a promise back instead? 为什么在 Node.js 中使用 async-await 时会丢失堆栈跟踪? - Why do I lose stack trace when using async-await in Node.js? 如何在以下情况下正确使用 async-await? - How do I use async-await properly in the following situation? 如何在循环中等待 promise 完成? (不使用异步等待) - How do I wait for a promise to finish inside a loop? (without using async-await) 我对异步等待感到困惑 - I am confused with async-await Async-Await:即使一个错误,如何在多个等待调用中获取数据? - Async-Await: How to get data in multiple await calls even when there is an error in one? 使用“异步等待”模式时,Mocha单元测试尚未完成 - Mocha unit test not finalized when using the 'async-await' pattern 当我使用 reactnative 时,如何在 useEffect 中使用异步等待? - how can i use async await in useEffect when i use reactnative?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM