在react redux和redux工具包中获取导入类型和切片的不同错误



我是redux in react的新手,我试图通过构建待办事项列表应用程序来找到自己的立足点,当我使用reducer时,我会遇到不同的错误,这是我的代码

对于SLICE。

import { createSlice } from "@reduxjs/toolkit";
const todoSlice = createSlice({
name: "todo",
initialState: [
{ id: 1, title: "Learn React", completed: true },
{ id: 2, title: "Learn Redux", completed: false },
{ id: 3, title: "Learn React-Redux", completed: false },
{ id: 4, title: "Learn React-Router", completed: false }],
reducer: {
addTodo: (state, action) => {
const newTodo = {
id: Math.random(),
title: action.payload.title,
completed: false
};
state.push(newTodo)
},
deleteTodo: (state, action) => {
state.filter((todo) => todo.id !== action.payload.id)
}
}
}
)
export const { addTodo, deleteTodo } = todoSlice.actions;
export default todoSlice.reducer

对于Store,

import { configureStore } from "@reduxjs/toolkit";
import todoRedcuer from './todoSlice'
export const store = configureStore({
reducer: {
todo: todoRedcuer
}
});

现在,每当我想在它们各自的组件中使用这些减速器时,不同的导入类型都会出现不同的错误例如

import addTodo from "../redux/todoSlice";

对于这种导入类型,我得到这个错误

未捕获类型错误:无法读取未定义(读取"类型"(的属性

并且对于此导入类型,

import { addTodo }from "../redux/todoSlice";

我收到这个错误

List.js:8未捕获类型错误:(0,redux_todoSlice_WEBPACK_IMPORTED_MODULE_2_.addTodo(不是函数

这是我调度代码的组件

import React from "react";
import { useDispatch } from "react-redux";
import addTodo from "../redux/todoSlice";
const TodoForm = () => {
const [Todo, setTodo] = React.useState();
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
dispatch(
addTodo({
title: Todo,
})
);
};
return (
<div className="flex items-center flex-col justify-center">
<h1 className="my-8">To-Do List</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
name="todo"
placeholder="Add todo..."
value={Todo}
onChange={(e) => setTodo(e.target.value)}
className="px-6 py-3 rounded-xl outline-0 bg-slate-100 mr-10"
/>
<button
className="px-6 py-3 rounded-xl outline-0 bg-blue-500"
>
Add..
</button>
</form>
<h3>{Todo}</h3>
</div>
);
};
export default TodoForm;

请问我做错了什么或错过了什么?感谢您的时间和帮助

在您的行中

import addTodo from "../redux/todoSlice";
// this is a shortcut for
import { default as addTodo } from "../redux/todoSlice";

您实际上是在导入切片减少器,而不是操作。

改为:

import { addTodo } from "../redux/todoSlice";

相关内容

  • 没有找到相关文章

最新更新