[英]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 中。
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.