【问题标题】:Dynamic state update in mobx react typescriptmobx react typescript中的动态状态更新
【发布时间】:2021-07-06 02:08:16
【问题描述】:

我想要一个只接受在 mobx 中声明的状态的函数。我目前有这个代码。

class DialogStore {
    status: boolean = false;
    title: string = '';
    content: string = '';
    btnText: string = ''; 
    icon: JSX.Element | string = '';
    type: 'success' | 'error' = 'success';

    constructor() {
        makeAutoObservable(this);
    }

    toggle(status: boolean) {
        this.status = status
    }

    success(content: string) {
        this.type = 'success';
        this.status = true;
        this.content = content;
    }

    error(content: string) {
        this.type = 'error';
        this.status = true;
        this.content = content;
    }
}

我想添加这样的动态函数:

update(payload: TypeOfState) {
    Object.keys(payload).forEach(property => {
        this[property] = payload[property];
    })
}

我试图将any 作为我的有效负载类型,但它给了我这个错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DialogStore'。我希望有效载荷只接受我在顶部声明的状态。

【问题讨论】:

    标签: reactjs typescript mobx mobx-react


    【解决方案1】:

    如果我对您的理解正确,您希望使用单一功能而不是 toggle、success 和 error?

    这样的事情对你的情况有用吗?

    class DialogStore {
      // ...
    
      update(payload: StateToUpdate) {
        Object.keys(payload).forEach((property) => {
          this[property] = payload[property];
        });
      }
    }
    
    type StateToUpdate = Partial<Pick<DialogStore, 'status' | 'type' | 'content'>>
    
    

    为避免 TS 错误,您可以在 tsconfig.json 中完全禁用标志 "suppressImplicitAnyIndexErrors": true 或使用一些类型转换:

        Object.keys(payload).forEach((property) => {
          (this as any)[property] = payload[property as keyof StateToUpdate];
        });
    

    我认为目前没有简单的方法可以缓解 TS 中的此类错误,但我可能错了。

    【讨论】:

    • 您理解正确,它会产生错误Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'DialogStore'。可能是因为它是一个类并且调用this[property],其中property 也可能意味着像success() 或error() 这样的函数
    • 我已经稍微更新了我的答案。我不太确定如何在完全类型安全的情况下实现这样的功能
    • 我使用(this as any)[property] = (payload as any)[property] 解决了这个问题。然后我为状态创建了一个类型,然后将其投射到有效负载上。我意识到在这上面放任何东西确实会给打字稿带来任何不利影响,因为我唯一想要输入的是有效载荷道具
    猜你喜欢
    • 2016-11-04
    • 2021-08-18
    • 1970-01-01
    • 2018-12-18
    • 2020-05-01
    • 2019-06-15
    • 1970-01-01
    • 2021-07-09
    • 2021-05-03
    相关资源
    最近更新 更多