- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在做一个 React JS 项目。我正在使用 React Hooks(功能组件)和 React query .
我通常在功能组件中按如下方式运行/执行查询。
const ItemList = (props) => {
let getItemsQuery = useQuery([ 'get-items' ], getItems, {
retry: false,
refetchOnWindowFocus: false
});
// The rest of the code goes here
}
基本上,查询是在加载组件时执行的,因此也进行了 API 调用。
现在,我正在寻找一种只有在单击按钮时才能执行查询的方法。
return (
<button onClick={() => {
//make the call. The value or value might be overridden when the API call is made when the Call 2 button is clicked
}}>Call 1</button>
<button onClick={() => {
//make the call. The value or value might be overridden when the API call is made when the Call 1 button is clicked
}}>Call 2</button>
)
如您在上面的虚拟代码中所见,注释解释了我想要实现的目标。我该怎么做?
最佳答案
从 this answer 中提取:
import React, { useState } from "react";
import { useQuery } from "react-query";
const App = (props) => {
const [text, setText] = useState("");
// use your async request (axios, fetch, etc)
// useQuery expects a Promise so we can safely use this instead
const emulateFetch = async (_) => {
// axios.get (...)
console.log(`Passing ${text} to fetch`);
return new Promise((resolve) => {
resolve([{ data: "ok" }]);
});
};
const handleClick = () => {
// manually refetch
refetch();
};
const { isLoading, error, data, refetch } = useQuery(
["key", { text }],
emulateFetch,
{
refetchOnWindowFocus: false,
enabled: false // needed to handle refetchs manually
}
);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<p>Home page</p>
<input
type="text"
value={text}
onChange={(event) => setText(event.target.value)}
/>
<button onClick={handleClick}>Click me</button>
{JSON.stringify(data)}
</div>
);
};
export default App;
工作 sandbox .
关于reactjs - React Hooks 和 React 查询 (useQuery) : invoking the API call/query only when a button is clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64770279/
我遇到过这个 html: 上面的html和这个有什么区别: 最佳答案 来自MDN page on the tag : 对于 type 的属性标签,可能的值是: 提交:按钮将表单数据提交给服务器
Button button= (Button) findViewbyID(R.id.button); 和 Button button = new Button(this); 有什么区别? 最佳答案 有
我是一名优秀的程序员,十分优秀!