我已經抽象了一些將資料提取到它自己的服務中的邏輯。
import type { Todo } from './Todo';
class TodoService {
private async secretFetch() {
const todos = await fetch('https://jsonplaceholder.typicode.com/todos/');
return (await todos.json()) as Todo[];
}
async fetchTodos() {
const todos = await this.secretFetch();
return todos;
}
}
const todoService = new TodoService();
export default todoService;
我想將此方法用作 的引數useQuery,但我注意到當該方法在我的類中呼叫另一個方法時查詢失敗。
export default function App() {
const { data: todos, isLoading } = useQuery('todos', todoService.fetchTodos);
if (isLoading) {
return <p> Loading </p>;
}
if (todos.length === 0) {
return <p> There are no todos </p>;
}
return (
<ul>
{todos.map((todo) => (
<li> {todo.title} </li>
))}
</ul>
);
}
這是 Stack blitz 中的一個示例:https ://stackblitz.com/edit/react-ts-5uxsz5?file=App.tsx
uj5u.com熱心網友回復:
你失去了this參考
要么創建一個匿名函式
const { data: todos, isLoading } = useQuery('todos', () => todoService.fetchTodos());
或系結
const { data: todos, isLoading } = useQuery('todos', todoService.fetchTodos.bind(todoService));
uj5u.com熱心網友回復:
this在fetchTodos指向錯誤的背景關系中。
要么將 轉換fetchTodos為箭頭函式:
fetchTodos = async () => {
const todos = await this.secretFetch();
return todos;
}
或將其設定secretFetch為靜態方法并訪問它:
class TodoService {
private static async secretFetch() {
...
}
async fetchTodos() {
const todos = await TodoService.secretFetch();
return todos;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529115.html
標籤:反应班级反应查询
