【发布时间】:2020-07-01 08:00:50
【问题描述】:
我正在尝试像这样使用 mapStateToProps :
const mapStateToProps = (state: { logedIn: boolean; } ) => {
return {
logedIn: state.logedIn
}
}
我正在创建 typescript react 应用程序。 我尝试在我的编辑器中使用 ctrl 搜索来搜索已登录,并且发现它处于应为的初始状态。 但是当我在做 npm start 时,我收到了这个错误:
TypeError: Cannot read property 'logedIn' of undefined
Function.mapStateToProps [as mapToProps]
src/components/LogIn/Login.tsx:79
76 |
77 | const mapStateToProps = (state: { logedIn: boolean; } ) => {
78 | return {
> 79 | LogedIn: state.logedIn
80 | }
81 | }
82 |
这是我的初始状态
interface IAppState {
logedIn : Boolean;
}
const initialState : IAppState = {
logedIn : false
};
const reducer = (state = initialState, action : any) => {
switch (action.type) {
case actionTypes.LOG_IN:
return {
...state,
logedIn: true
}
case actionTypes.LOG_OUT:
return {
...state,
logedIn: false
}
}
}
创建商店:
export const store = createStore(reducer)
我在这里也遇到错误,说没有重载与“reducer”匹配
减速机:
import {actionTypes} from "./actionTypes";
export const LogedIn = () => {
return {
type:actionTypes.LOG_IN
}
}
export const LogOut = () => {
return {
type:actionTypes.LOG_OUT
}
}
有什么建议吗?我真的被这些卡住了
【问题讨论】:
-
能否添加reducer的代码?您在 createStore 中使用的 reducer 变量的类型是什么。
-
我更新了帖子。
-
用
const reducer:Reducer<IAppState>替换const reducer -
还有
import { Reducer } from 'redux'; -
现在它在 const reducer 上给了我这个错误:Reducer
TS2322: Type '(state: IAppState | undefined, action: any) => { logedIn: boolean; } | undefined' is not assignable to type 'Reducer<IAppState, AnyAction>'. Type '{ logedIn: boolean; } | undefined' is not assignable to type 'IAppState'. Type 'undefined' is not assignable to type 'IAppState'.
标签: reactjs typescript react-redux