gpt4 book ai didi

javascript - 类型 '{}' 不可分配给类型 'Readonly'

转载 作者:行者123 更新时间:2023-11-30 20:14:57 24 4
gpt4 key购买 nike

我正在尝试将存储注入(inject)到组件中,但它似乎不起作用。
这是类

import * as React from 'react';
import { inject, observer } from 'mobx-react';

import { FlightStore } from '../stores/FlightStore';

export interface HelloProps {
flightStore: FlightStore
}



@inject('flightStore')
@observer
class Hello extends React.Component<HelloProps, any> {

constructor(props: HelloProps) {
super(props);
this.state = {
//
}
}


componentWillMount() {
this.props.flightStore.getData();
}

render() {
return (
<div>

</div>
)
}
}

export default Hello;

它说 Type '{}' is not assignable to type 'Readonly<HelloProps>'.
Property 'flightStore' is missing in type '{}'
,这让我很困惑,因为我没有在任何地方声明任何数据类型,所以我不知道发生了什么。

这是商店

import { action, observable } from 'mobx';
import * as $ from 'jquery' ;


export class FlightStore {

@observable dataJ: any;

constructor() {
//
}

@action getData() {

$.ajax({
url: 'https://www.kayak.com/h/mobileapis/directory/airlines',
dataType: 'json',
cache: false,
success: (data: any) => {
this.dataJ = data;
console.log(data)
},
error: (xhr: any, status: any, err: any) => {
console.log(err);
}
})
console.log('I´m in getData')
}

}

这很奇怪,因为当我尝试输入“?”时在类里面

export interface HelloProps {
flightStore?: FlightStore
}

它说这个 this.props.flightStore => [ts] Object is possibly 'undefined'.在 ComponentWillMount()

更新

是的,错误发生在我尝试使用 <Hello/> 时没有传递 Prop 的组件,因为我使用的是 Mobx。
索引应用

import * as React from 'react';
import Hello from './components/Hello';

import stores from './stores';
import { Provider } from 'mobx-react';


export default class App extends React.Component {
render() {
return (
<Provider {...stores}>
<div>
<Hello />
</div>
</Provider>
);
}
}

最佳答案

我假设最初的错误是在您尝试将组件用作 <Hello/> 时发生的没有通过 Prop 。 Hello被声明为需要 flightStore支柱。你会希望 @inject会提供它并且 TypeScript 会知道您不必自己传递它,但这似乎不起作用。所以看看declaration of @inject :

// Ideally we would want to return React.ComponentClass<Partial<P>>,
// but TS doesn't allow such things in decorators, like we do in the non-decorator version
// See also #256
export function inject(
...stores: string[]
): <T extends IReactComponent>(target: T) => T & IWrappedComponent<T>
export function inject<S, P, I, C>(
fn: IStoresToProps<S, P, I, C>
): <T extends IReactComponent>(target: T) => T & IWrappedComponent<T>

如果你去 referenced issue ,您会发现问题未解决,并且有一些建议的解决方法。其中之一是将 prop 声明为可选,就像您在第二个版本中所做的那样,然后在访问它时使用非空断言:this.props.flightStore! .

关于javascript - 类型 '{}' 不可分配给类型 'Readonly<HelloProps>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com