使用promise错误测试createAsyncThunk

时间:2020-08-18 01:14:08

标签: redux-thunk redux-toolkit

我正在JS的Redux Toolkit中测试createAsyncThunk API,但出现错误,需要一些帮助。

我只是复制react Todo示例,我试图创建一个延迟添加todo函数来测试redux thunk。 这是AddTodo React Arrow功能组件

import React, { useState } from 'react';
import { connect, useDispatch } from 'react-redux';
import { delayAddToDo, addTodo } from './todosSlice';

const AddTodo = ({ addTodo, delayAddToDo }) => {
  const [todoText, setTodoText] = useState('');

  const dispatch = useDispatch();

  const onChange = e => {
    setTodoText(e.target.value);
  };

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          if (!todoText.trim()) {
            return;
          }
          dispatch(delayAddToDo(todoText));
          //addTodo(todoText);
          setTodoText('');
        }}
      >
        <input value={todoText} onChange={onChange} type="text" />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  );
};

const mapDispatchToProps = { addTodo, delayAddToDo };

export default connect(null, mapDispatchToProps)(AddTodo);

这是todosSlice

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

let nextTodoId = 0;

export const delayAddToDo = createAsyncThunk('todos/delayAddTodo', () => {
  console('delayAddTodo');

  const delayAdd = (resolve, reject) => {
    setTimeout(function () {
      resolve('Success!');
    }, 5);
  };

  return new Promise(delayAdd);
});

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo: {
      reducer: (state, action) => {
        console.log('adding todo');
        const { id, text } = action.payload;
        state.push({ id, text, completed: false });
      },
      prepare: text => {
        console.log('prepare');
        return { payload: { text, id: nextTodoId++ } };
      },
    },
    toggleTodo(state, action) {
      const todo = state.find(todo => todo.id === action.payload);
      if (todo) {
        todo.completed = !todo.completed;
      }
    },
  },
  extraReducers: {
    [delayAddToDo.fulfilled]: (state, action) => {
      console.log('fullfilled');
      //state = [];
    },
  },
});

export const { addTodo, toggleTodo } = todosSlice.actions;

export default todosSlice.reducer;

我在控制台中收到一条错误消息,说 在以下路径中的某个操作中检测到​​不可序列化的值:...

谢谢

1 个答案:

答案 0 :(得分:0)

我认为这是因为您正在解析一个不可序列化的函数。这样的东西怎么样?

const delayAdd = () => new Promise(resolve => {
  setTimeout(function () {
    resolve('Success!');
  }, 5);
})

export const delayAddToDo = createAsyncThunk('todos/delayAddTodo', async() => {
  const result = await delayAdd()

  return result;
});