0

我正在尝试将变量“结果”放入操作有效负载中,但无法定义它,因为它位于 try 块中。我不确定如何解决这个问题。我还是 Redux 的新手,这就是操作本身。

export const fetchMovies = async (endpoint, category) => {
    const isLoadMore = endpoint.search('page');
    try{
        const result = await (await fetch(endpoint)).json();
    } catch(error){
        this.setState({error: true});
        console.log(error);
    }

    return{
        type: HomeActionTypes.FETCH_MOVIES,
        payload: result, category, isLoadMore
    }
}

我尝试使用 let 在顶部初始化结果,但它没有解决问题。另外,我不确定我是否使用我在其中设置的变量正确设置了有效负载。例如,它们需要在 reducer 中使用,我的猜测是将有效负载中的项目称为 action.payload.result、action.payload.category、action.payload.isLoadMore,只要我需要在 reducer 中使用它们. 这是正确的方法吗?感谢您为帮助回答我的问题所做的任何贡献。

4

1 回答 1

1

你可以采取不同的方法。第一个,你正在尝试的那个,你必须在对应的词法范围内将变量声明resultlet(这样你就可以修改它的值),所以在这种情况下,在try大括号之外和函数声明内,以便return可以访问它的值。

export const fetchMovies = async (endpoint, category) => {
    const isLoadMore = endpoint.search('page');
    let result = null
    try{
        result = await (await fetch(endpoint)).json();
    } catch(error){
        this.setState({error: true});
        console.log(error);
    }

    return{
        type: HomeActionTypes.FETCH_MOVIES,
        payload: result, category, isLoadMore
    }
}

我宁愿遵循的另一种方法是在大括号中移动快乐流的所有逻辑,并在try大括号中管理错误流中返回的操作catch

export const fetchMovies = async (endpoint, category) => {
    try{
        const isLoadMore = endpoint.search('page');
        const result = await (await fetch(endpoint)).json();
        return{
          type: HomeActionTypes.FETCH_MOVIES,
          payload: result, category, isLoadMore
        }
    } catch(error){
        // Rather than modifying the state, use a defined error action to trigger the proper error flow and logic.
        console.log(error);
        return{
          type: HomeActionTypes.FETCH_MOVIES_ERROR, // To be defined in the way you desire to be able to manage it as the execution of this action
          payload: error
        }
    }
}
于 2020-03-02T00:24:40.747 回答