rematch+ts遇到的问题

1,643 阅读1分钟

从官网看例子,写代码,遇到几个ts验证过不了的问题。 例子代码

models/count.js代码:

import { createModel } from '@rematch/core'
import { RootModel } from '.'

const count = createModel<RootModel>()({
    state: 0, // initial state
    reducers: {
        // handle state changes with pure functions
        increment(state, payload: number = 1) {
            return state + payload
        },
    },
    effects: (dispatch) => ({
        // handle state changes with impure functions.
        // use async/await for async actions
        async incrementAsync(payload?: number, state?: any) {
            console.log('This is current root state', state, payload);
            await new Promise(resolve => setTimeout(resolve, 1000))
            dispatch.count.increment(payload)
        },
    }),
})

models/index.js代码:

import { Models } from '@rematch/core'
import count from './count'

export interface RootModel extends Models<RootModel> {
    count: typeof count
}

const models: RootModel = { 
  count,
}
export default models

报错1:ESLint: Dependency cycle detected.(import/no-cycle)

原因: 在上面两个文件中,index.js中依赖了count.js,count.js中又引入了index.js,造成了循环依赖

解决办法: 将count.js中的rootModel引入改为import type { RootModel } from '.',导入类型, 这是语法静态类型检查-flow工具的一个语法

报错2:Expected 0 arguments, but got 1.

错误位置:modles/count.js的effects函数中

    effects: (dispatch) => ({
        // handle state changes with impure functions.
        // use async/await for async actions
        async incrementAsync(payload?: number, state?: any) {
            console.log('This is current root state', state, payload);
            await new Promise(resolve => setTimeout(resolve, 1000))
            dispatch.count.increment(payload)    //此处报错:Expected 0 arguments, but got 1.
        },
    }),

此处调用的是在reduce中定义的increment方法,可看到此处ts的定义是payload参数为可选,默认值为1,可传参或不传参,但不知道为何出现上面的报错Expected 0 arguments, but got 1.

increment(state, payload: number = 1) {
...
}

解决办法:increment的方法的payload类型设置为payload: number | undefined

increment(state, payload: number | undefined) {
    return state + (Number(Boolean(payload))
}

猜测原因:因为incrementAsyncpayload?: number参数也是可选项,如果未传参时,payload此时为undefined,那么在dispatch.count.increment(payload)时,会匹配错误。