[英]Redux thunk - async action scope changes
技術:反應,打字稿
我正在嘗試在 redux 中編寫一個異步操作創建器,它從服務器獲取數據,但是我返回的內部函數的范圍發生了變化並且什么都不知道
動作/電影.ts
import MovieServer from '../../server/Movie';
import { setMovies } from './movieActions';
const fetchMovies = () => {
console.log(MovieServer);
return async (dispatch: any) => {
console.log(MovieServer);
const movies: Movie[] = await MovieServer.fetchMovies();
dispatch(setMovies(movies));
}
}
服務器/電影.ts
import Movie from "../models/movie";
import { serverURL } from "./config";
const fetchMovies = async (): Promise<Movie[]> => {
let movies: Movie[] = [];
try {
const response = await fetch(serverURL + "/api/movie", {
method: "GET"
});
if (!response.ok || response.status !== 200) {
throw new Error("bad response");
} else {
movies = await response.json();
}
} catch (err) {}
return movies;
}
export default { fetchMovies };
當我運行代碼時,第一個日志輸出是MovieServer
的函數MovieServer
,第二個日志輸出是undefined
。
所以在內部函數里面有些東西不好,它會拋出一個錯誤。
我嘗試將內部函數包裝在.bind(this)
但它引發了 ts 編譯錯誤: The containing arrow function captures the global value of 'this'.
感謝您的回答,但這是服務器的問題,我不知道為什么它會影響功能的范圍,但我解決了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.