建议和反馈

请填写你的反馈内容

使用React.JS和GraphQL的动态博客

2019-10-01 ·1645次阅读 ·读完需要1分钟


在本教程中,我们将向您展示如何使用React,GraphQL和Cosmic JS创建一个简单的博客。这将是建立在现代技术堆栈之上的最快,最轻量的博客。

学习目标

本食谱介绍如何使用:


•GraphQL 

•如何为动态路由安装下一个路由

•用于我们的服务器端Web应用程序框架的Express.js。

•Next.js作为我们的React Universal框架。

•Axios,用于我们基于承诺的HTTP客户端,以将内容从Cosmic JS GraphQL API获取。

先决条件

•本地安装了Node.js 

•确保全局安装了yarn 

•您应该了解JavaScript和GraphQL

Steps

Make sure that you have Node.js and NPM installed on your machine, if not, visit the Node.js website to install the latest version.

Let’s start by creating a folder for our app. In your favorite terminal run the following commands:

mkdir simple-react-blog

cd simple-react-blog

Now let’s add a package.json file to import all of our dependencies for our app:

vim package.json

Add the following to our package.json file:


It’s a pretty light dependency list for a pretty light app. So what we will install is:

1. Axios for our promise-based HTTP client to get content from to the Cosmic JS GraphQL API.

2. Next.js as our React Universal framework.

3. Next routes for dynamic routes.

4. Express for our server-side web app framework.

5. React to handle our user interface.

Our scripts are necessary for starting our app in production and development.

Run the following command to install our dependencies:

npm i

Building Our Blog

Next, let’s begin building our blog pages. Create a pages folder and add the index.js file:

vim index.js

and add the following to index.js:

import axios from 'axios'

import _ from 'lodash'

import Footer from './partials/footer'

import Header from './partials/header'

import helpers from '../helpers'

import config from '../config'


export default class extends React.Component {

static async getInitialProps({ req }) {

const query = `{

objects(bucket_slug: "${config.bucket.slug}") {

_id

type_slug

slug

title

metadata

created_at

}

}`

return await axios.post(`https://graphql.cosmicjs.com/v1`, { query })

.then(function (response) {

return {

cosmic: {

posts: _.filter(response.data.data.objects, { type_slug: 'posts' }),

global: _.keyBy(_.filter(response.data.data.objects, { type_slug: 'globals' }), 'slug')

}

}

})

.catch(function (error) {

console.log(error)

})

}

render() {

if (!this.props.cosmic)

return <div>Loading...</div>

return (

<div>

<Header cosmic={ this.props.cosmic }/>

<main className="container">

{

this.props.cosmic.posts &&

this.props.cosmic.posts.map(post => {

const friendly_date = helpers.friendlyDate(new Date(post.created_at))

post.friendly_date = friendly_date.month + ' ' + friendly_date.date

return (

<div className="card" data-href={`/${post.slug}`} key={post._id}>

{

post.metadata.hero.imgix_url &&

<a href={`/${post.slug}`} className="blog-post-hero blog-post-hero--short" style={{ backgroundImage: `url(${post.metadata.hero.imgix_url})`}}></a>

}

<div className="card-padding">

<h2 className="blog__title blog__title--small">

<a href={`/${post.slug}`}>{post.title}</a>

</h2>

<div className="blog__author">

<a href={`/author/${post.metadata.author.slug}`}>

<div className="blog__author-image" style={{ backgroundImage: `url(${post.metadata.author.metafields[0].imgix_url}?w=100)`}}></div>

</a>

<div className="blog__author-title">by <a href={`/author/${post.metadata.author.slug}`}>{post.metadata.author.title}</a> on {post.friendly_date}</div>

<div className="clearfix"></div>

</div>

<div className="blog__teaser droid" dangerouslySetInnerHTML={{__html: post.metadata.teaser}}></div>

<div className="blog__read-more">

<a href={`/${post.slug}`}>Read more...</a>

</div>

</div>

</div> 

)

})

}

</main>

<Footer />

</div>

)

}

}


here are a few things happening here:

1. We are importing our essential modules: Axios, Lodash, and other helpers and components.

2. We are pulling in some partials: Header and Footer.

3. We query the Cosmic JS GraphQL API to only return the stuff we need: _id, type_slug, slug, title, metadata and created_at.

4. We set the main props in our component to the `cosmic` object. And use lodash to parse through Posts and Global Object types.

5. We return our posts array data and image URLs into our main blog feed.

Single Post Query

For our single post, we add a `post` property to our props. Post is found by matching the query.slug to the Object slug:

const gql_query = `{

objects(bucket_slug: "${config.bucket.slug}") {

type_slug

slug

title

content

metadata

created_at

}

}`

return await axios.post(`https://graphql.cosmicjs.com/v1`, { query: gql_query })

.then(function (response) {

return {

cosmic: {

posts: _.filter(response.data.data.objects, { type_slug: 'posts' }),

global: _.keyBy(_.filter(response.data.data.objects, { type_slug: 'globals' }), 'slug'),

post: _.find(response.data.data.objects, { slug: query.slug }),

}

}

})

.catch(function (error) {

console.log(error)

})

}


Conclusion

This is the simple Blog app created with React and GraphQL. We have also used some libraries like next.js and express.


评论(0)问答(0)
请先登录或注册

请先登陆或注册

相关推荐

兰悠易:主流币BTC ETH LTC 11.18晚间行情分析

现在各币种都处于下行阶段,就连主流币也逃脱不出下跌的命运;不过整体走势还是在笔者的预料之中进行,若是有跟上笔者思路操作的朋友,应该获利良多吧;没有跟上的朋友,也不用太过担心,好的行情比比皆是,能及时把......
兰悠易 · 2019-11-18
41阅读 · 0赞赏 · 0问答

王佳柏:空方持续发力 走势依旧保持下行

比特币今日整体走势以下行为主,主要分两个阶段下跌:第一阶段是在凌晨六点之后,由于多次向上试探未果后承压回落,跌势维持了数小时之后,渐渐的收回以低位8419结束第一次的下行,随即转为低位震荡运行的走势;......
王佳柏 · 2019-11-18
78阅读 · 0赞赏 · 0问答

李向午:比特币空头强势高压,多头能否稳住支撑。

李向午:比特币空头强势高压,多头能否稳住支撑。  BTC行情分析  比特币昨日以一个阳十字星收盘,价格延续早几天的下跌趋势。从小时图中可以看出今日比特币开盘价格保持震荡上行节奏,早间六时开始价格下跌直......
李向午 · 2019-11-18
43阅读 · 0赞赏 · 0问答

王佳柏:比特币震荡区间下移 可见空方继续占据主导低位

比特币早间行情处于8550一线高位震荡,可是在早间一根带有长上影线的阴K改变了震荡走势的命运,行情开始不断的向下滑动,并回踩下方的支撑点位,此时正处于8450一线震荡运行;如果在此处“摔跤”真是不应该......
王佳柏 · 2019-11-18
73阅读 · 0赞赏 · 0问答

谈喻凯:BTC如期破位继续承压 EOS ETH操作建议

  投资千万条,风险第一条;策略千百种,哪个适合我;思路没跟上,踏空两行泪。关注谈喻凯公众號币圈散户联盟,精选全球最准行情分析,消息面,技术面为你指引解读,带你把握行情,瞄准良机,稳健交易。    截......
谈喻凯 · 2019-11-18
133阅读 · 0赞赏 · 0问答

兰悠易:比特币上行不成 回调向下寻找有力支撑

比特币日线图中,K线接连两日收阳,向上最高触碰到8585,而在今日高位再次创新,向上突破8600到达高点8620位置,不过新的起点还未站稳,就成了这次上行的真高点位;多方动力的减弱,便给了空方可趁之机......
兰悠易 · 2019-11-18
161阅读 · 0赞赏 · 0问答

Diva

1214

LK币

2

粉丝

31

笔记

感谢"Diva"

这篇精彩的笔记,目前已经帮助

  • 0
  • 1
  • 6
  • 4
  • 5
喜欢0
链客社群 加入

微博进入

商务合作>

广告投放>

公司名称:北京链客行科技有限公司

联系方式:010-67707199

ICP备案号:京ICP备18032136号

Copyright:链客区块链技术问答社区 版权所有

感谢您的提问,问题被社区永久收入以便新人查看。一定要记得采纳最佳答案哦!加油!

感谢您的善举,每一次解答会成为新人的灯塔,回答被采纳后获得20算力和相应的LK币奖励

您将赞赏给对方2LK币的奖励哦!感谢您的赞赏!

您将赞赏给对方2LK币的奖励哦!感谢您的赞赏!