第二次获取结果



晚上好,我有一个带有onclick事件的按钮,该事件在单击时启动ObjectCard(),其中结果是根据x文本框中的输入更改的对象。除了在第一次点击它总是返回未定义或以前的结果(x的旧值)。你能帮助我并解释为什么吗?谢谢你!

let carta = "";
function ObjectCard(){
let x = document.getElementById("searchtext").value;
const url = "https://api.scryfall.com/cards/named?fuzzy=";
return fetch( url + x)
.then(response => {
return response.json();
})
.then(response => carta = response)
.then (console.log(carta))
};

这是带有onclick事件的按钮

<button className="btn inline-block px-6 py-2.5 bg-blue-600 text-white font-medium text-xs leading-tight uppercase rounded-r-lg shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700  focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out flex items-center transition-all ease-in-out hover:-translate-y hover:scale-125 hover:rounded duration-300" type="button" id="button-addon2" onClick={ObjectCard}>
<Link to="/searchpage"><svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="search" className="w-4" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path fill="currentColor" d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path>
</svg></Link>
</button>

我认为在这种情况下你应该使用async/await语句,例如:

let carta = "";
async function ObjectCard(){
const inputValue = document.getElementById("searchtext").value; // Renamed "x"
const url = "https://api.scryfall.com/cards/named?fuzzy=";
const response = await fetch( url + inputValue ); // Response from fetch without parsing to json
const parsedResponse = await response.json(); // Parsing response
carta = parsedResponse
return parsedResponse;
}

尽管如此,我还是建议你抽象你的服务方法,并这样做:

let carta = "";
const inputValue = document.getElementById("searchtext").value;  // Renamed "x"
async function getCard(searchedCard){
const url = "https://api.scryfall.com/cards/named?fuzzy="  + searchedCard;
const response = await fetch(url); // Response from fetch without parsing to json
const parsedResponse = await response.json(); // Parsing response
return parsedResponse;
}
getCard(inputValue).then(res => carta = res);

最新更新