reactjs - Redux Toolkit 问题,获取 Cannot destruct 属性,因为它未定义

标签 reactjs redux

嘿,大家好,我正在尝试使用 redux 工具包,但遇到了一个奇怪的问题 我明白:

Cannot destructure property 'currentRequestId' of 'getState(...).toys' as it is undefined

vs code 告诉我查询之前的等待是: 'await' 对此表达式的类型没有影响

即使我在代码中设置了 currentRequestId,但 currentRequestId 确实没有显示在商店中

我从他们的网站复制了示例并对其进行了修改,也许我的 axios 调用会杀死它? 我可以看到由于某种原因我的调用甚至没有被执行。

我不知道如何实现像示例中所示的 UserApi,所以我使用常规的 axios 调用。

我的代码:

import React from 'react'
import { createAsyncThunk, createSlice, unwrapResult  } from '@reduxjs/toolkit'
import axios from 'axios'
import { useDispatch,useSelector } from 'react-redux'

 export const query = createAsyncThunk(
  '/api/toys',
  async (criteria, { getState, requestId }) => {
    const { currentRequestId, loading } = getState().toys
    if (loading !== 'pending' || requestId !== currentRequestId) {
      return
    }

    const response = await axios.get('http://localhost:3030/api/toys')
    return response.data
  }
)

export const ToySlice = createSlice({
  name: 'toys',
  initialState: {
    entities: [],
    loading: 'idle',
    currentRequestId: undefined,
    error: null
  },
  reducers: {},
  extraReducers: {
    [query.pending]: (state, action) => {
      if (state.loading === 'idle') {
        state.loading = 'pending'
        state.currentRequestId = action.meta.requestId
      }
    },
    [query.fulfilled]: (state, action) => {
      const { requestId } = action.meta
      if (state.loading === 'pending' && state.currentRequestId === requestId) {
        state.loading = 'idle'
        state.entities.push(action.payload)
        state.currentRequestId = undefined
      }
    },
    [query.rejected]: (state, action) => {
      const { requestId } = action.meta
      if (state.loading === 'pending' && state.currentRequestId === requestId) {
        state.loading = 'idle'
        state.error = action.error
        state.currentRequestId = undefined
      }
    }
  }
})

export const Test = () => {
  const { toys, loading, error } = useSelector(state => state.test)
  const dispatch = useDispatch()


  const fetchAllToys = async userId => {
    try {
      const resultAction = await dispatch(query())
      const toys = unwrapResult(resultAction)
      console.log("Test -> user", toys)
      return toys
    } catch (err) {
    console.log("UsersComponent -> err", err)

    }
  }
return(<div>
    Hello
    <button onClick={()=>fetchAllToys()}>Fetch</button>
</div>)
  // render UI here
}


export const selectCount = state => state.counter.value;

export default ToySlice.reducer;

商店:

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
import Test from '../features/Test/test'
export default configureStore({
  reducer: {
    counter: counterReducer,
    test:Test
  },
});

示例链接: https://jsfiddle.net/3xq7Lng2/

文档:

https://redux-starter-kit.js.org/api/createAsyncThunk

最佳答案

您的 thunk 正在尝试访问 getState().toys.currentRequestId

但是,您没有 state.toys 键,因为您没有将名为 toys 的字段传递给 configureStore。您正在定义 state.counterstate.Test,但没有 state.toys,因此它将是未定义的。

我不知道其中包含 ToySlice 的文件名是什么。根据导入,我假设它实际上是名为features/Test/test.js的文件。

立即解决的办法是将商店设置代码更改为:

import toysReducer from '../features/Test/test';

export default configureStore({
  reducer: {
    counter: counterReducer,
    toys: toyReducer
  },
});

这将导致 state.toys 存在。

您还需要更新当前正在执行 useSelector(state => state.test) 的组件,并将其更改为 state => state.toys.

从那里,我建议将文件夹和文件名更改为 features/toys/toysSlice.js 并相应地更新导入语句。

关于reactjs - Redux Toolkit 问题,获取 Cannot destruct 属性,因为它未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61762301/

相关文章:

javascript - 传递一个空的 Prop (没有 api 值)来 react 组件

javascript - 使用 .map 比较数组 (ReactJS)

javascript - 本地存储的更改未触发事件监听器

javascript - 如何正确地将 React 中随状态传递的 Date 对象放入 datepicker 中?

javascript - 获取 React material-UI Autocomplete 中的值

reactjs - 测试自定义 Hook : Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

reactjs - React JavaScript 文件中用于 HTML 支持的 Atom 包

javascript - 更新 Prop react 后如何更新组件

reactjs - 用户使用 redux 登录后需要刷新浏览器才能显示数据

javascript - 为什么react-redux将状态与恒等(===)运算符进行比较?对象不能以这种方式进行比较