【问题标题】:Access to API using Redux使用 Redux 访问 API
【发布时间】:2021-08-12 06:36:31
【问题描述】:

我有一个 react-redux 应用程序。我需要调用 API 并在我的组件中使用它。该应用程序在 utills 中使用 fetch in 函数调用。 所有函数都是这样分组和导出的:

export const sportTeam = {
  getBasketballTeam,
  getBasketballTeamById,
}
function   getBasketballTeam() {
   let token = store.getState().UserReducer.token;
fetch(
    actions.GET_BASKETBALLTEAM,
{
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    }
  )
    .then((res) => {
      if (res.status == 200 ) {
        return res.json();
      }
    })
    .then((response) => {
      console.log(response);
    })
    .catch((err) => {
      console.log(err);
    });
}

getBasketballTeam 包含一个对象数组。 如何获取 getBasketballTeam 并在视图中的组件中使用它来返回包含此数据的列表?

【问题讨论】:

    标签: reactjs api redux


    【解决方案1】:

    您不希望您的 getBasketballTeam 函数直接通过 store.getState() 访问商店。

    你想要的是一个“thunk”动作创建者,当你dispatch它时,它会获取商店实例作为参数。

    你想要的流程是这样的:

    1. 组件通过useSelector(或connect)持续监听篮球队状态。
    2. 组件安装。
    3. 组件调度 getBasketballTeam 操作。
    4. 操作从 API 获取数据。
    5. Reducer 将数据从操作保存到状态。
    6. 状态更新。
    7. 组件使用状态中的新数据重新渲染。

    最简单的方法是使用 Redux Toolkit 中的 createAsyncThunk 函数。此帮助程序通过分派单独的错误操作来处理所有错误。试试这样的:

    行动:

    export const fetchBasketballTeam = createAsyncThunk(
      "team/fetchBasketballTeam",
      async (_, thunkAPI) => {
        const token = thunkAPI.getState().user.token;
        if ( ! token ) {
          throw new Error("Missing access token.");
        }
        const res = await fetch(actions.GET_BASKETBALLTEAM, {
          method: "GET",
          headers: { Authorization: `Bearer ${token}` }
        });
        if (res.status !== 200) {
          throw new Error("Invalid response");
        }
        // what you return is the payload of the fulfilled action
        return res.json();
      }
    );
    

    减速机:

    const initialState = {
      status: "idle",
      data: null
    };
    
    export const teamReducer = createReducer(initialState, (builder) =>
      builder
        .addCase(fetchBasketballTeam.pending, (state) => {
          state.status = "pending";
        })
        .addCase(fetchBasketballTeam.fulfilled, (state, action) => {
          state.status = "fulfilled";
          delete state.error;
          state.data = action.payload;
        })
        .addCase(fetchBasketballTeam.rejected, (state, action) => {
          state.status = "rejected";
          state.error = action.error;
        })
    );
    

    商店:

    export const store = configureStore({
      reducer: {
        team: teamReducer,
        user: userReducer,
      }
    });
    

    组件:

    export const BasketballTeam = () => {
      const { data, error, status } = useSelector((state) => state.team);
      const dispatch = useDispatch();
    
      useEffect(
        () => {
          dispatch(fetchBasketballTeam());
        },
        // run once on mount
        // or better: take the token as an argument and re-run if token changes
        [dispatch]
      );
    
      if (status === "pending") {
        return <SomeLoadingComponent />;
      }
    
      if (!data) {
        return <SomeErrorComponent />;
      }
    
      // if we are here then we definitely have data
      return <div>{/* do something with data */}</div>;
    };
    

    【讨论】:

      【解决方案2】:

      收到回复后,您需要做以下事情

      1. 调用dispatch函数来存储REDUX状态下接收到的数据。
      2. 现在,当您有数据处于 redux 状态时,您可以使用 useSelector() 来获取该状态并在您的 jsx 文件中使用它。

      【讨论】:

        猜你喜欢
        • 2020-09-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2017-09-20
        • 2019-01-21
        • 2018-01-10
        • 2016-07-20
        • 2020-04-28
        相关资源
        最近更新 更多