首页 > 解决方案 > 无法使用打字稿在 react-redux 中调度操作

问题描述

我正在使用 react redux typescript 开发一个 TODO 应用程序。我无法发送动作。我是 redux 的新手,所以陷入了困境。我正在创建一个事件 onclick handleSubmitButton 然后它抛出调度错误。有人可以帮我吗?

AddToDo.tsx

const AddToDo: React.FC = () => {
    const [inputValue, setInputValue] = useState<string>("");

    const handleSubmitButton = (e: React.MouseEvent<HTMLButtonElement>)=> {
        e.preventDefault()
        console.log(inputValue, "inputValue");
        dispatch(addTodo(inputValue))
    }

    return (
        <div>
            <form noValidate>
                <div className="form-group">
                    <label htmlFor="todoitem">Todo Item:</label>
                    <input type="text" className="form-control" placeholder="Enter Text" value={inputValue} id="todoitem" onChange={handleEditTodoItem} />
                </div>
                <button type="submit" className="btn btn-primary" onClick={handleSubmitButton}>Submit</button>
            </form>
        </div>
    )
}

export default connect()(AddToDo)

以下是我的操作代码 -

export const addTodo = (name: string): AddTodoAction => (
   {
    type: ActionTypes.ADD_TODO,
    payload: {
      todo: {
        id: nextId++,
        name: name,
        done: false
      }
    }
  }
)

现在我的减速器代码 -

export function reducer(state: State = initialState, action: Action) {

  switch (action.type) {
    case ActionTypes.ADD_TODO: {

      const todo = action.payload.todo

      return {
        ...state,
        todos: [...state.todos, todo]
      }
    }
}
}

标签: reactjstypescriptredux

解决方案


您收到“调度错误”的原因dispatch可能是undefined. 这是因为您未能:

import { useDispatch } from 'react-redux'
// ...
const dispatch = useDispatch();

如果使用 hooks 连接到 redux,你不需要“连接”任何东西,也不需要写mapDispatchToProps. 只需useSelector并且useDispatch足以连接到 redux 商店,这会带来更友好的体验。


推荐阅读