【问题标题】:Does not exist on type 'DefaultRootState'. TS2339在“DefaultRootState”类型上不存在。 TS2339
【发布时间】:2021-08-21 12:53:21
【问题描述】:

我正在尝试在登录表单输入值中实现 react-redux。 我已经为 redux 状态添加了值,但我无法从状态对象单独访问数据。

以下是详细信息:

App.js 文件中

console.log(useSelector((state) => state));

给出结果{email: "demo@demo.com" , password: "123456"} .我无法使用

访问状态对象内的电子邮件
console.log(useSelector((state) => state.email));

它给出的错误是 'email' does not exist on type 'DefaultRootState'. TS2339

这是reducer.js 文件

let formValues = {
email: "",
password: "",
};

export const inputReducer = (state = formValues, action) => {
  switch (action.type) {
    case "inputValue":
      return { ...state, [action.name]: action.inputValue };
    default:
      return state;
  }
};

这是action.txt 文件

export const handleChange = (name: string, inputValue: string) => {
    return {
      type: "inputValue",
      name: name,
      inputValue: inputValue,
    };
}

【问题讨论】:

    标签: react-redux store reducers


    【解决方案1】:

    我写了一个函数来解决这个问题:

    function getProperty<T, K extends keyof T>(o: T, propertyName: K): T[K] {
        return o[propertyName]; // o[propertyName] is of type T[K]
    }
    

    您必须将您的对象作为第一个参数传递,然后是您的属性名称(这里是电子邮件或密码)。

    如果您想一次获取所有属性,则必须将它们封装在一个对象属性中,如下所示:

    { value : {email:"alan.turing@gmail.com",password:"123" } }
    

    【讨论】:

    • 这个答案对我没有帮助,但问题与我的问题完全相同。我在我的反应应用程序中使用的是 javascript 而不是打字稿。
    • @artworkjpm 你找到解决方案了吗?
    【解决方案2】:

    我可能迟到了,但我想提供解决方案。基本上,当您没有在 useSelector 钩子中提供输入时,就会出现这种类型的错误消息

    根据文档React-Redux 所述:

    使用 configureStore 不需要任何额外的输入。你会, 但是,想要提取 RootState 类型和 Dispatch 类型,所以 可以根据需要引用它们。

    在您的代码块中缺少 RootState 类型,这可以在您的商店文件中声明如下

    import {createStore} from 'redux';
    ----------
    const store = createStore(rootReducer);
    export default store;
    
    export type RootState = ReturnType<typeof store.getState>;
    

    在您的 .tsx 或 .jsx 文件中,您要使用 react-redux 钩子 useSelector 访问您的商店值,添加如下类型。

    useSelector((state:RootState) => state)
    

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 2020-11-24
      • 2016-03-14
      • 2017-02-25
      • 1970-01-01
      • 2021-11-24
      • 2019-01-11
      • 2021-05-08
      相关资源
      最近更新 更多