【问题标题】:initializing state in react-redux on typescript在 typescript 上的 react-redux 中初始化状态
【发布时间】:2018-07-23 19:13:57
【问题描述】:

我正在尝试使用 initState 初始化存储。我的 initstate 对象是,

const initState :any = {
    squares: Array<number>(9).fill(null),
    curState: false
}

我正在创建这样的商店。

let store = createStore(appReducer, initState);

这会在打字稿中引发错误

TS2339:类型“number[]”上不存在属性“fill”。

我的 tsconfig.json 文件

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "moduleResolution": "node"
    },
    "include": [
        "./src/**/*"
    ]
}

如果我将 initState 声明更改为

const initState :any = {
    squares: Array<number>(9),
    curState: false
}

然后它可以工作,但不会创建数组。

【问题讨论】:

    标签: reactjs typescript react-redux


    【解决方案1】:

    将“es2015.core”添加到您的 tsconfig.json 的 lib 属性中:

    {
        "compilerOptions": {
            "lib": [
                "dom",
                "es5",
                "scripthost",
                "es2015.core",
            ]
        }
    }
    

    请注意,如果未指定 lib 属性(如在您的原始示例中),则此属性的默认值为 ["dom", "es5", "scripthost"]。因此,您还需要添加这些值以避免删除这些默认库。

    这是lib 编译器选项的文档:https://www.typescriptlang.org/docs/handbook/compiler-options.html(向下滚动到--lib)。

    【讨论】:

      【解决方案2】:

      使用数组展开创建一个新数组,然后用 null 填充每个值。这应该是有效的。

      const initState: any = {
          squares: [...new Array(9).fill(null)],
          curState: false,
      };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-02
        • 2016-09-22
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 1970-01-01
        • 2019-01-04
        • 1970-01-01
        相关资源
        最近更新 更多