首页 > 解决方案 > 无法解析模块`./__generated__/AppQuery.graphq

问题描述

我正在尝试使用中继将我现有的 react-native 项目连接到 GrapghQl。__generated__文件夹未创建 AppQuery.graphql.js

参考链接

错误- 在此处输入图像描述

包.json

{
  "name": "farmcom",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "relay": "relay-compiler --src ./src --schema ./schema.graphql",
    "relayw": "relay-compiler --src ./src --schema ./schema.graphql --watch",
    "test": "jest"
  },
  "dependencies": {
    "graphql": "^14.0.2",
    "prop-types": "^15.6.2",
    "react": "16.5.0",
    "react-native": "^0.57.2",
    "react-native-collapsible": "^1.2.0",
    "react-native-splash-screen": "^3.0.6",
    "react-native-vector-icons": "^6.0.2",
    "react-navigation": "^2.17.0",
    "react-relay": "^1.7.0",
    "relay": "^0.8.0-1"
  },
  "devDependencies": {
    "babel-jest": "23.6.0",
    "babel-plugin-relay": "^1.7.0",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.48.0",
    "react-test-renderer": "16.5.0",
    "relay-compiler": "^1.7.0",
    "schedule": "^0.4.0"
  },
  "jest": {
    "preset": "react-native"
  }
}

.babelrc

{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": ["relay"]
}

中继环境.js

const { Environment, Network, RecordSource, Store } = require("relay-runtime");

const source = new RecordSource();
const store = new Store(source);

var myHeaders = new Headers();
// myHeaders.append('Access-Control-Allow-Headers', 'Content-Type');
// myHeaders.append("Content-Type", "multipart/form-data");
myHeaders.append("Content-Type", "application/json");

//'https://us-west-2.api.scaphold.io/graphql/narrow-pigs'
//'https://api.graph.cool/relay/v1/cj9z8yz7ig1zb0121dl0uwk2n

// Define a function that fetches the results of an operation (query/mutation/etc)
// and returns its results as a Promise:
function fetchQuery(operation, variables, cacheConfig, uploadables) {
  return fetch("https://api.graph.cool/relay/v1/cjd4f6t7c35vn0159xw0lfij1", {
    method: "POST",
    headers: myHeaders,
    mode: "cors",
    body: JSON.stringify({
      query: operation.text, // GraphQL text from input
      variables
    })
  }).then(response => {
    return response.json();
  });
}

// Create a network layer from the fetch function
const network = Network.create(fetchQuery);

const environment = new Environment({
  network,
  store
});

export default environment;

应用程序.js

import React, { Component } from "react";
import { StyleSheet, Text } from "react-native";
import SplashScreen from "react-native-splash-screen";
import { graphql, QueryRenderer } from "react-relay";
import ListAccount from "./src/listAccount";
import environment from "./src/relay.environment";


const AppQuery = graphql`
  query AppQuery($count: Int!, $after: String) {
    viewer {
      ...listAccount_viewer
    }
  }
`;

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      authentic: false
    };
  }

  isAuthentic = authentic => {
    this.setState({ authentic });
  };

  componentDidMount() {
    SplashScreen.hide();
  }

  renderCard(item) {
    return <Text>{item.text}</Text>;
  }

  render() {
    return (
      <QueryRenderer
        environment={environment}
        query={AppQuery}
        variables={{
          count: 1
        }}
        render={({ error, props }) => {
          if (error) {
            return <Text>{error.message}</Text>;
          } else if (props) {
            return (
              <View>
                <ListAccount viewer={props.viewer} />
              </View>
            );
          }
          return <Text>App Loading</Text>;
        }}
      />
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center"
  }
});

listAccount.js

import React, { Component } from "react";
import {
  Text,
  View,
  Button,
  Checkbox,
  TextInput,
  TouchableOpacity
} from "react-native";
import { graphql, createPaginationContainer } from "react-relay";
import Account from "./account";

class ListAccount extends Component {
  _loadMore() {
    if (!this.props.relay.hasMore()) {
      console.log(`Nothing more to load`);
      return;
    } else if (this.props.relay.isLoading()) {
      console.log(`Request is already pending`);
      return;
    }
    this.props.relay.loadMore(1);
  }

  render() {
    return (
      <View>
        <Text>
          {this.props.viewer.allAccounts.edges.map(({ node }, i) => (
            <Account key={i} account={node} />
          ))}
        </Text>
        <Button onPress={() => this._loadMore()} title="more..." />
      </View>
    );
  }
}

export default createPaginationContainer(
  ListAccount,
  {
    viewer: graphql`
      fragment listAccount_viewer on Viewer {
        allAccounts(first: $count, after: $after, orderBy: createdAt_DESC)
          @connection(key: "ListAccount_allAccounts") {
          edges {
            node {
              ...account_account
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    `
  },

  {
    direction: "forward",
    query: graphql`
      query listAccountForwardQuery($count: Int!, $after: String) {
        viewer {
          ...listAccount_viewer
        }
      }
    `,
    getConnectionFromProps(props) {
      return props.viewer && props.viewer.allAccounts;
    },
    getFragmentVariables(previousVariables, totalCount) {
      return {
        ...previousVariables,
        count: totalCount
      };
    },
    getVariables(props, paginationInfo, fragmentVariables) {
      return {
        count: paginationInfo.count,
        after: paginationInfo.cursor
      };
    }
  }
);

account.js

import React, { Component } from "react";
import { Text } from "react-native";
import { graphql, createFragmentContainer } from "react-relay";

class Account extends Component {
  render() {
    return <Text>{this.props.account.acno}</Text>;
  }
}

export default createFragmentContainer(
  Account,
  graphql`
    fragment account_account on Account {
      acno
    }
  `
);

标签: react-nativegraphqlrelayjs

解决方案


推荐阅读