reactjs - 无法使用打字稿在 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]
}
}
}
}
解决方案
您收到“调度错误”的原因dispatch
可能是undefined
. 这是因为您未能:
import { useDispatch } from 'react-redux'
// ...
const dispatch = useDispatch();
如果使用 hooks 连接到 redux,你不需要“连接”任何东西,也不需要写mapDispatchToProps
. 只需useSelector
并且useDispatch
足以连接到 redux 商店,这会带来更友好的体验。
推荐阅读
- mongodb - Docker 实例连接到本地 Mongo:无法绑定到地址
- python - 如何直接从c数据转换为numpy对象
- azure-cognitive-search - Azure 搜索同义词映射未返回预期结果
- excel - 查找日期 = 或 < 特定日期并返回另一列中的值所需的公式
- reactjs - 如何覆盖特定类别的反应材料组件
- python - 对于大小为 5 的轴 1,索引 5 超出范围
- vba - 如何使用 AutoIT 在 Word 中单击 ActiveX 控件?
- asp.net - 从已部署的 Azure 应用服务中提取 MachineKey
- python - 在 SciPy (Python) 中从拟合 PDF 生成随机样本
- javascript - LoopBack 和 MongoDb,embadsMany 关系返回空数组