我是第一次使用Redux和Typescript。我不明白为什么当我尝试使用对象时商店不想接受reducer
let store = createStore(counter); //error on counter
是在Typescript中设置了错误的类型还是使用了错误的reducer?
错误文本:
常数计数器:(状态:人员,操作:任意)=〉数字|undefined没有与此调用匹配的重载。为#2769贡献一个翻译
过载1/2,'(减速机:还原剂〈个人,任何〉,增强剂?:StoreEnhancer〈未知,未知〉|未定义):Store〈IPersson,any〉',出现以下错误。贡献一份#2772的翻译
类型的参数'(state:I人员,操作:任意)=〉数字|未定义的“不能赋值给类型为”Reducer〈IPerson,any〉“的〉参数。翻译:我期待的是Reducer〈IPerson,any〉,但您通过了(状态:I人员,操作:任意)=〉数字|未定义的
import React from 'react';
import logo from './logo.svg';
import {createStore} from 'redux'
function App() {
interface IPerson{
name:string,
age:number
}
const increment = () => {return {type: 'INCREMENT'}}
const decrement = () => {return {type: 'DECREMENT'}}
const counter = (state:IPerson , action:any) =>{
switch(action.type){
case'INCREMENT':
return state.age + 1;
case'DECREMENT':
return state.age - 1;
}}
let store = createStore(counter);
store.subscribe(()=>console.log(store.getState()));
return (
<div className="App">
<button onClick={(()=>store.dispatch(increment()))}>increment</button>
<button onClick={(()=>store.dispatch(decrement()))}>decrement</button>
<h1>Hello world!</h1>
</div>
);
}
export default App;
1条答案
按热度按时间nbnkbykc1#
如果其他两种情况不匹配,则您的减速器不会
return
。一般来说,您在这里使用的是一个非常旧的Redux样式(现代Redux是代码的1/4)和一些不好的做法(永远不要在组件中调用
store.dispatch
!)。我真的建议您阅读有关modern Redux的内容,并遵循official tutorial,而不是遵循您目前为止阅读的任何资源。