當我嘗試實例化一個擴展爲Relay.Mutation
的類時,我遇到了一個非常奇怪的TypeError,它帶有react-relay
。我已使用create-react-app my-app --scripts-version=react-scripts-ts
創建了一個簡單的Typescript項目來演示此問題。使用Typescript引發的React Relay(react-relay)引發TypeError:對象原型可能只是一個Object或null:undefined
每當我跑yarn start
,這是我所看到的:
這個錯誤並沒有真正意義的我: TypeError: Object prototype may only be an Object or null: undefined
我只是試圖實例我自己擴展的一個新實例Relay.Mutation
類。我對React Relay世界和ES6/Typescript一般都很陌生,所以它可能是我錯過的一些愚蠢的東西。
在這個簡單的項目中,我直接使用DefinitelyTyped repository中定義的示例類。
我不應該能夠使用類,像這樣:
const atm = new AddTweetMutation({ text: 'asdf', userId: '1123' });
這裏是AddTweetMutation.tsx
類的樣子:
import * as Relay from 'react-relay';
interface Props {
text: string;
userId: string;
}
interface State {
}
export default class AddTweetMutation extends Relay.Mutation<Props, State> {
public getMutation() {
return Relay.QL`mutation{addTweet}`;
}
public getFatQuery() {
return Relay.QL`
fragment on AddTweetPayload {
tweetEdge
user
}
`;
}
public getConfigs() {
return [{
type: 'RANGE_ADD',
parentName: 'user',
parentID: this.props.userId,
connectionName: 'tweets',
edgeName: 'tweetEdge',
rangeBehaviors: {
'': 'append',
},
}];
}
public getVariables() {
return this.props;
}
}
這裏是整個Hello.tsx
陣營組成:
import * as React from 'react';
import AddTweetMutation from '../mutations/AddTweetMutation';
export interface Props {
name: string;
enthusiasmLevel?: number;
}
class Hello extends React.Component<Props, {}> {
render() {
const atm = new AddTweetMutation({ text: 'asdf', userId: '1123' });
console.log(atm);
const { name, enthusiasmLevel = 1 } = this.props;
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic. :D');
}
return (
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
</div>
);
}
}
export default Hello;
// helpers
function getExclamationMarks(numChars: number) {
return Array(numChars + 1).join('!');
}
這就是我的package.json
的樣子:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/jest": "^20.0.6",
"@types/node": "^8.0.19",
"@types/react": "^16.0.0",
"@types/react-dom": "^15.5.2",
"@types/react-relay": "^0.9.13",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-relay": "^1.1.0",
"react-scripts-ts": "2.5.0"
},
"devDependencies": {},
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject"
}
}
更新:分型目前不能有效反應繼電器> 1.x的請參閱thread on github for this issue。我也使用解決方法更新了我的回購。
檢查'Relay.Mutation'確實存在。庫的版本和類型不匹配。做一個'console.log('relay.mutation',Relay.Mutation)'(或用'')來查明。 –
unional
你說得對。 'Relay.Mutation'返回undefined。似乎沒有與庫的版本相匹配的類型。解決這個問題的正確方法是什麼?爲什麼突變不再存在?對不起,超新的Typescript,只是想找出一個工作策略。 –
我假設它在這裏與React v15.5有關:https://facebook.github.io/react/blog/2017/04/07/react-v15.5.0.html –