简体   繁体   中英

Redux thunk - async action scope changes

Technologies: react, typescript


The problem

I'm trying to write an async action creator in redux that fetches the data from the server, but the scope of the inner function that i'm returning changes and dosen't know anything


Code

actions/Movie.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));
    }
}

server/Movie.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 };

When I run the code, the first log output is the function decleration of MovieServer , the second log output is undefined .

so inside the inner function somethings not good and its throwing an error.


What i've tried

I tried wraping the inner function in a .bind(this) but it throws a ts compilation error: The containing arrow function captures the global value of 'this'.

感谢您的回答,但这是服务器的问题,我不知道为什么它会影响功能的范围,但我解决了

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM