使用
apollo传送门做关于react连接graphql的项目
一、项目搭建
-
1、使用
create-react-app创建一个react项目 -
2、安装
react-graphql的基础包yarn add apollo-boost graphql react-apollo -
3、在
package.json中配置代理{ ... "proxy":"http://localhost:8000/" } -
4、修改
react项目的入口文件(把client传递到子组件中)import ApolloClient from 'apollo-boost'; import { ApolloProvider } from 'react-apollo'; // Pass your GraphQL endpoint to uri const apolloClient = new ApolloClient({ uri: 'http://localhost:8000/graphql/' }); const ClientRender = () => { let appComponent = ( <ApolloProvider client={apolloClient}> <App /> </ApolloProvider> ) ReactDOM.render(appComponent, document.getElementById('root')); }; export default ClientRender(); -
5、在组件中使用
query查询语句(参考test1.jsx) -
6、函数方式的组件可以参考
test2.jsx(个人更习惯使用class构造组件的方式) -
7、传递参数参考
test4.jsx和test5.jsx