Redux-Toolkit = 无法使用 useSelector 显示 API 响应数据

Posted

技术标签:

【中文标题】Redux-Toolkit = 无法使用 useSelector 显示 API 响应数据【英文标题】:Redux-Toolkit = can't display API Response Data by using useSelector 【发布时间】:2021-11-24 00:33:52 【问题描述】:

我尝试使用react hook form创建过滤器表单来过滤stockMovement报告。流程是用户填写过滤器表单并单击过滤器提交按钮将过滤器值发送到getStockMovement函数以调用API,我成功了获取 API 响应数据,但无法使用 useSelector 将响应数据显示到我的界面。我已经把reducer和组件代码放在下面了。

reportStockMovementSlice 代码

    import  createSlice, createAsyncThunk, createSelector from '@reduxjs/toolkit';
    import axios from 'axios';
    
    export const getStockMovement = createAsyncThunk('report/stockMovement/getStockMovement', async( params,dispatch)=> 
        const by = params;
        const response = await axios.get(`http://localhost:8100/getpickuppointbyid/pickupPointId="pickupPointId":$by`);
        const data = await response.data.results[0];
        console.log("getStockMovement",data) --- response data successfull
         return data === undefined ? null : data;
    );
    
    const reportStockMovementSlice = createSlice(
        name: 'report/stockMovement',
        initialState:
            stockMovement:[] ,
        reducers: ,
        extraReducers: 
            [getStockMovement.fulfilled]: (state, action) =>
             state.stockMovement =action.payload;
    );
    
    export const selectStockMovement = createSelector(
        (state) => (
           stockMovement:state.stockMovement
        ), (state) =>  state
      );
   export default reportStockMovementSlice.reducer;









>  StockMovementFilter Component Code
>         
>         import  getStockMovement, selectStockMovement   from '../store/reportStockMovementSlice';
>         const result= useSelector(selectStockMovement);
>         console.log ("result---",result)   - undefined 
>      function StockMovementFilter(props)    
>          /// button submit pass filter values to API
>         function submit ()
>         
>          dispatch(getStockMovement(getValues())).then(action=>
>           console.log ("---action---",action) --- this have response result
>          )
>             console.log ("-----value",getValues()) - this value get from react hook form
>         
       
  export default withReducer('report', reducer) (StockMovementFilter);




> --- main stockMovementReport 
>     function StockMovementReport() 
>       return (
>           
>           <FusePageCarded
>               classes=
>                   content: 'flex',
>                   // contentCard: 'overflow-hidden',
>                     toolbar: 'min-h-56 h-56 items-end',
>                   header: 'min-h-52 h-52 sm:h-136 sm:min-h-136'
>               
>               // header=<StockMovementHeader />
>               content=<div> <div className="row"><StockMovementFilter/></div> <div
> className="row"><StockMovementTable /></div> </div>
>               innerScroll
>           />
>       
>       );
>     
>     
>     export default  withReducer('report',reducer) (StockMovementReport);

商店合并

import reportStockMovement from './reportStockMovementSlice';

const reducer = combineReducers(
    reportStockMovement 
);

export default reducer;

witReducer 代码

import  injectReducer  from 'app/store/index';

const withReducer = (key, reducer) => WrappedComponent => 
    injectReducer(key, reducer);

    return props => <WrappedComponent ...props />;
;

export default withReducer;

【问题讨论】:

你是如何建立你的商店的?你也可以分享一下那个代码吗? @phry 嗨,好的。我分享了上面的部分代码。 @phry redux devtools show report-> reportStockMovement -> stockMovement : "name":"yyy") @phry 但我尝试了 export const selectStockMovement = state=>state.report.reportStockMovement.stockMovement;也不能(未定义) 【参考方案1】:

您的商店数据路径错误。

选择器始终从您的商店的根状态中进行选择 - 在您的情况下,您只有更多的嵌套。

我建议您使用 Redux Devtools 来查看您的商店是如何嵌套的,但是从您的 combineReducers 调用中,我假设您的数据路径类似于 state.reportStockMovement,所以您会想要这样做像

    export const selectStockMovement = (state) => state.reportStockMovement.stockMovement

顺便说一句,如果您真的只是从商店中选择数据,则不需要使用 createSelector - 仅当您在那里进行复杂计算或返回新对象时才使用它,在这种情况下可能没有必要。

我会推荐阅读https://redux.js.org/recipes/computing-derived-data

【讨论】:

redux devtools show reportStockMovement -> stockMovement : "name":"yyy")

以上是关于Redux-Toolkit = 无法使用 useSelector 显示 API 响应数据的主要内容,如果未能解决你的问题,请参考以下文章

“AsyncThunkAction”Redux-toolkit 类型上不存在属性“then”

Redux-Toolkit 和 React Hooks - 存储更改不会触发重新渲染

Redux-Toolkit createAsyncThunk with Typescript

在 Redux-Toolkit 中使用 for 循环的问题

如何在 Storybook 中使用 redux-toolkit?

如何在 Redux-toolkit 中使用两个不同的切片?