Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用Redux访问API_Reactjs_Api_Redux - Fatal编程技术网

Reactjs 使用Redux访问API

Reactjs 使用Redux访问API,reactjs,api,redux,Reactjs,Api,Redux,我有一个react redux应用程序。我需要调用API并在我的组件中使用它。在utills中使用fetch-in函数调用应用程序。 所有功能都按如下方式分组和导出: export const sportTeam = { getBasketballTeam, getBasketballTeamById, } function getBasketballTeam() { let token = store.getState().UserReducer.token; fetch(

我有一个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并在视图中的组件中使用它以返回包含此数据的列表?

获得响应后,需要执行以下操作

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

  • 您不希望您的
    getBasketballTeam
    函数直接通过
    store.getState()
    访问存储

    您需要的是一个“thunk”操作创建者,当您
    dispatch
    store实例时,它将其作为参数获取

    您想要的流程如下所示:

  • 组件使用
    useSelector
    (或
    connect
    )持续侦听篮球队状态
  • 组件安装
  • 组件分派一个
    getBasketballTeam
    操作
  • 操作从API获取数据
  • Reducer将数据从操作保存到状态
  • 状态更新
  • 组件使用状态中的新数据重新呈现

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

    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);
        });
    }
    
    行动:

    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>;
    };
    
    export const basketballsteam=()=>{
    const{data,error,status}=useSelector((state)=>state.team);
    const dispatch=usedpatch();
    使用效果(
    () => {
    调度(获取篮球队());
    },
    //挂载一次
    //或者更好:将令牌作为参数,并在令牌更改时重新运行
    [快讯]
    );
    如果(状态==“待定”){
    返回;
    }
    如果(!数据){
    返回;
    }
    //如果我们在这里,那么我们肯定有数据
    返回{/*对数据做点什么*/};
    };