react+apollo+prisma入门demo搭建---3、Mutations组件编写(Creating Links)

react+apollo+prisma入门demo搭建—3、Mutations组件编写(Creating Links)

根据HOW TO GRAPHQL官网的例子,做了些对最新版的改动,适合最新框架的学习。

本系列文章注重前端方面的开发,对于node方面的放在下一个系列。在此过程中有任何问题,都欢迎在评论中提问,会及时反馈

系列目录:

第一章. Frontend开始
第二章. Queries组件编写(Loading Links)
第三章. Mutations组件编写(Creating Links)
第四章. 页面路由
第五章. 身份验证

Mutations组件编写(Creating Links)

为了照顾更加全面的读者,我写的会尽量详细,熟练的开发者可进行快速选择性的阅读

准备react组件

和Query组件相似Mutation组件也类似遵循那三个步骤

我们首先在components文件夹中创建CreateLink.js

import React, { Component } from 'react'

class CreateLink extends Component {
  state = {
    description: '',
    url: '',
  }

  render() {
    const { description, url } = this.state
    return (
      <div>
        <div className="flex flex-column mt3">
          <input
            className="mb2"
            value={description}
            onChange={e => this.setState({ description: e.target.value })}
            type="text"
            placeholder="A description for the link"
          />
          <input
            className="mb2"
            value={url}
            onChange={e => this.setState({ url: e.target.value })}
            type="text"
            placeholder="The URL for the link"
          />
        </div>
        <button onClick={`接下来将要编写这里`}>Submit</button>
      </div>
    )
  }
}

export default CreateLink

这是一个简单的包含两个input的组件,填写的信息会同步到组件state中,用于接下来的请求。

编写mutation

先在CreateLink头部中定义我们需要的mutation请求

const POST_MUTATION = gql`
  mutation PostMutation($description: String!, $url: String!) {
    post(description: $description, url: $url) {
      id
      createdAt
      url
      description
    }
  }
`

然后用以下代码替换button

<Mutation mutation={POST_MUTATION} variables={{ description, url }}>
  {postMutation => <button onClick={postMutation}>Submit</button>}
</Mutation>

最后引入需要的依赖

import { Mutation } from 'react-apollo'
import gql from 'graphql-tag'

一个可以发送变更请求的组件就完成了,现在我们将组件放在App.js中,看看效果

import React, { Component } from 'react'
import CreateLink from './CreateLink'

class App extends Component {
 render() {
  return <CreateLink />
}
}

export default App

运行两个服务,然后在网页上的两个input框中,分别输入:

点击submit按钮,如果一切顺利的话,在GraphQL server的playground中编写以下query

{
  feed {
    links {
      description
      url
    }
  }
}

然后你就可以看到有数据返回,其中多出了你刚刚添加的那条记录

{
  "data": {
    "feed": {
      "links": [
        // ...
        {
          "description": "The best learning resource for GraphQL",
          "url": "www.howtographql.com"
        }
      ]
    }
  }
}

成功编写了可以发送变更的组件!马上开始下一步的旅程吧。

页面路由

本章项目github 分支地址

https://github.com/zust-hh/simple-hackernews/tree/Frontend-topic3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值