[英]React-apollo Typescript errors when using graphql to pass props to higher order component
我在嘗試將 React class 組件連接到我的 Apollo 緩存數據時遇到了一些問題,目前這只是本地緩存數據。
我正在關注這里的文檔,但是當我訪問這樣的數據時,VSCode 和 Webpack 會拋出錯誤: this.props.data.playing
,這就是我希望訪問它的方式。 盡管如此,在瀏覽器中這會返回正確的數據。 但是,如果我訪問這樣的數據: this.props.data.data.playing
檢查通過但在瀏覽器控制台中引發錯誤( Cannot read property 'playing' of undefined
)。 所以我有理由確定這是一個類型定義錯誤,但我不確定我哪里出錯了。
我應該指出 NPM 和所有軟件包都已更新。
type AudioData = {
bpm: number;
beatsPerBar: number;
playing: boolean;
metronomeSound: string;
playPosition: number;
playStartTime: number;
};
type Response = {
data: AudioData;
};
class ConnectedWorkspaceAudio extends React.Component<
ChildProps<{}, Response>
> {
_context: AudioContext;
_scheduler: Scheduler;
_recorder: Recorder;
constructor(props: ChildProps<{}, Response>) {
super(props);
}
componentDidMount(): void {
/***/
}
componentDidUpdate(prevProps: ChildProps<{}, Response>): void {
console.log(this.props.data.playing); // Fails type check, prints correctly in browser.
if (this.props.data.data) {
if (this.props.data.data.playing && !prevProps.data.data.playing) { // Passes type check, gives console error in browser.
useApolloClient().writeData({ data: { playing: true } });
}
if (!this.props.data.data.playing && prevProps.data.data.playing) {
useApolloClient().writeData({ data: { playing: false } });
}
}
}
/** There's some more methods including render() I don't believe are relevant. */
}
const WORKSPACE_AUDIO_QUERY = gql`
query AudioState {
bpm @client
beatsPerBar @client
playing @client
metronomeSound @client
playPosition @client
playStartTime @client
}
`;
const WorkspaceAudio = graphql<{}, Response>(WORKSPACE_AUDIO_QUERY)(
ConnectedWorkspaceAudio
);
export { WorkspaceAudio };
這不是輸入錯誤 - 嘗試訪問未准備好的數據的典型錯誤 - 通常在render()
中,當數據尚未到達時。
將console log
if (this.props.data.data) {
... 和錯誤的日志參數之后,應該是console.log(this.props.data.data.playing);
- 響應命名data
(有點誤導)。
這里的解決方案是不將AudioData
類型包裝到Response
中,盡管他們在文檔中使用了該模式。 我更新了以下幾行:
class ConnectedWorkspaceAudio extends React.Component<
ChildProps<{}, AudioData>
{
...
const WorkspaceAudio = graphql<{}, AudioData>(WORKSPACE_AUDIO_QUERY)(
ConnectedWorkspaceAudio
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.