我一直在学习Typescript,通过创建一个任务管理器应用程序与React和Redux。我试图发送我的状态到Redux作为一个字典数组,但问题是,我需要声明一个空的字典数组之前,我可以通过它发送我的状态。
下面是我的App.tsx
文件:
import React, { FC, useState } from "react"
import { useSelector, useDispatch } from "react-redux"
import TodoList from "./Components/TodoList"
import NameTodo from "./Components/NameTodo"
import { RootState } from "./todoStore"
import { createTodoCard } from "./todoReducer"
interface TodoListTemplate {
title: string,
id: number,
}
const App: FC = () => {
// Contains all the generated todo-lists
const [generatedTodoList, setGeneratedTodoList] = useState<any[]>([]);
const selector = useSelector((state: RootState) => { return state.todo });
const dispatch = useDispatch();
const generateTodoList = (): void => {
// Sending this to the Redux state as an array of dictionaries
const todoList: TodoListTemplate = {
title: selector.todoCardName,
id: Math.floor(Math.random() * 10000),
}
setGeneratedTodoList([...generatedTodoList, todoList]);
// Reducer that would send todoList to the Redux state
dispatch(createTodoCard(generatedTodoList));
}
return (
...
)
}
export default App
下面是我的todoReducer.ts
文件:
import { createAction, createReducer, PayloadAction } from '@reduxjs/toolkit'
export const update = createAction<any[]>('update')
export const toggleNaming = createAction<boolean>('toggleNaming')
export const addTodoName = createAction<string>('addTodoName')
//This is the reducer that would send the todoList to the array of dictionaries
export const createTodoCard = createAction<Record<string, number>[]>('createTodoCard')
export const todoReducer = createReducer(
{
todoList: [''],
toggleNamingMenuState: false,
todoCardName: '',
// It should be sent here
todoCard: [],
},
(builder) => {
builder
.addCase(update, (state, action: PayloadAction<any[]>) => {
state.todoList = action.payload
})
.addCase(toggleNaming, (state, action: PayloadAction<boolean>) => {
state.toggleNamingMenuState = action.payload
})
.addCase(addTodoName, (state, action: PayloadAction<string>) => {
state.todoCardName = action.payload
})
.addCase(createTodoCard, (state, action: PayloadAction<Record<string, number>[]>) => {
state.todoCard = action.payload
})
}
)
export default todoReducer
我试过使用Record<k, v>
,但我不确定我是否正确使用它。
下面是显示的错误:
Type 'Record<string, number>[]' is not assignable to type 'never[]'.
Type 'Record<string, number>' is not assignable to type 'never'.
感谢您提前回复:)
1条答案
按热度按时间0ejtzxu11#
声明数组时,需要指定它的类型。
要么用这种方法做,要么开足马力为它创建一个接口,或者为reducer初始化式指定整个对象的类型。例如: