react api_如何在WordPress REST API之上构建React应用

react api

by Andrey Pokrovskiy

通过安德烈·波克洛夫斯基(Andrey Pokrovskiy)

如何在WordPress REST API之上构建React应用 (How to build React apps on top of the WordPress REST API)

UPDATE 06/16/2017:I updated the project to use ReactRouter 4 and Webpack 2. Some parts were refactored and simplified. Included links to the frontend React demo and Wordpress backend demo.

更新 06/16/2017 我更新了项目以使用ReactRouter 4和Webpack2。对某些部分进行了重构和简化。 包含指向前端React演示和Wordpress后端演示的链接。

WordPress is a powerful content management tool. But when it comes to developing on top of it, can be quite frustrating. WordPress’s crazy mixture of HTML and PHP loops can often prove unintuitive to grasp and hard to maintain.

WordPress是功能强大的内容管理工具。 但是,要在其之上进行开发,可能会令人沮丧。 WordPress疯狂地将HTML和PHP循环混合在一起,通常难以理解且难以维护。

There’s a light at the end of the tunnel, though! Starting with version 4.7, WordPress comes with a built-in REST API, and plugins are no longer required. This makes it easier to use WordPress strictly as a backend data storage or CMS, while allowing for a totally custom front end solution of your choice.

隧道尽头有灯! 从4.7版开始,WordPress带有内置的REST API,并且不再需要插件。 这使将WordPress严格用作后端数据存储或CMS变得更容易,同时允许您选择完全定制的前端解决方案。

You no longer need to have a local WordPress installation and deal with setting up vhosts. Your local development process can be limited to building the front end that is connected with a WordPress installation hosted on a remote server.

您不再需要在本地安装WordPress并处理设置虚拟主机。 您的本地开发过程可能仅限于构建与托管在远程服务器上的WordPress安装连接的前端。

In this article I’m going to use ReactJS to build the front end part of the application, React Router for routing, and Webpack for bundling it all together. I’ll also show you how to integrate Advanced Custom Fields, for those of us who have come to rely on it as a tool to create an intuitive solution for our clients.

在本文中,我将使用ReactJS来构建应用程序的前端部分,使用React Router进行路由选择,并使用Webpack将它们捆绑在一起。 我还将向您展示如何集成高级自定义字段,对于那些依赖于此作为工具为我们的客户创建直观解决方案的工具。

The stack looks like this:- ReactJs- React Router v4- Alt (for Flux implementation)- Webpack v2

堆栈如下所示: -ReactJs -React Router v4 -Alt(用于Flux实现) -Webpack v2

GitHub repo: https://github.com/DreySkee/wp-api-reactReact frontend demo url: http://wp-api-react.surge.sh/Wordpress backend demo url: http://andreypokrovskiy.com/projects/wp-api-react/wp-adminUser: demoPass: wp-react-demo

GitHub repohttps : //github.com/DreySkee/wp-api-react React前端演示网址http: //wp-api-react.surge.sh/ Wordpress后端演示网址http : //andreypokrovskiy.com/ projects / wp-api-react / wp-admin 用户 :demo 密码 :wp-react-demo

项目设置 (Project setup)

Let’s name the project “wp-api-react”. To follow along, first thing you need to do is include this in your package.json and run npm install:

让我们将项目命名为“ wp-api-react”。 要进行后续操作,您需要做的第一件事就是将其包含在package.json中,然后运行npm install

Install webpack and webpack-dev-server globally as well if you have not done this already:

如果还没有全局安装webpack和webpack-dev-server,请执行以下操作:

npm i webpack webpack-dev-server -g

npm i webpack webpack-dev-server -g

Now in the project folder create wepack.dev.js for development configuration and webpack.production.js with configuration for building the project for production.

现在,在项目文件夹中创建wepack.dev.js发展配置和webpack.production.js与配置构建项目进行生产。

Paste this in webpack.dev.config.js:

将此粘贴到webpack.dev.config.js

And this in webpack.production.config.js:

而这在webpack.production.config.js

Create “src” folder in the project root and create index.html inside of it. The index.html file will include this chunk of code:

在项目根目录中创建“ src”文件夹,并在其中创建index.htmlindex.html文件将包含以下代码块:

Now let’s add a few more folders to the project. Inside of the “src” folder create “scripts” folder and inside of “scripts” create “components”, “flux” and index.js file. This structure will help to keep files organized.

现在让我们向项目添加更多文件夹。 在“ src”文件夹内创建“ scripts”文件夹,在“ scripts”内创建“ components”,“ flux”和index.js文件。 这种结构将有助于保持文件井井有条。

By now the folder structure should look like this:

现在,文件夹结构应如下所示:

wp-api-react/node_modules/src/ — — scripts/ — — — components/ — — — flux/ — — — index.js — — index.html package.json webpack.config.js

WP-APIReact/ - node_modules / - SRC / - - 脚本/ — — — 组件/ — — — 助焊剂/ — — — index.js — — index.html package.json webpack.config.js

index.js is the entry point for Webpack and it will hold all routes for the project. Let’s include React, React Router and basic routing structure in the file:

index.js是Webpack的入口点,它将保存该项目的所有路由。 让我们在文件中包括React,React Router和基本路由结构:

index.js is referencing Home component in imports. We need to create it in the “components” folder. Home.js will be the template component for the homepage. Include this in the file:

index.js在导入中引用Home组件。 我们需要在“ components”文件夹中创建它。 Home.js将成为主页的模板组件。 将此包含在文件中:

If you run npm start in the terminal inside of the project folder and open http://localhost:8080/ in the browser you should see a “Hello world!” message. If you start changing files Webpack will hot-reload the page for you.

如果您在项目文件夹内的终端中运行npm start并在浏览器中打开http:// localhost:8080 / ,您应该会看到一个“ Hello world!”。 信息。 如果您开始更改文件,Webpack将为您热重新加载页面。

助焊剂 (Flux with Alt)

Now it’s time to implement flux using Alt. You will need to create three new folders inside of the “flux” folder: “alt”, “stores” and “actions”:

现在是时候使用Alt实现通量了 。 您将需要在“ flux”文件夹中创建三个新文件夹:“ alt”,“ stores”和“ actions”:

wp-api/ node_modules/ src/ — — scripts/ — — — flux/ — — — — alt/ — — — — actions/ — — — — stores/ — — — components/ — — — — Home.js — — — index.js — — index.htmlpackage.jsonwebpack.config.js

wp-api / node_modules / src / — — 脚本/ — — — 助焊剂/ ---- alt / ---- 动作/ ---- 商店/ --- 组件/ — — — — Home.js — — — index.js — — index.htmlpackage.jsonwebpack.config.js

Create Alt.js inside of the “alt” folder and paste this in the file:

在“ alt”文件夹中创建Alt.js并将其粘贴到文件中:

All this file is doing is exporting the Alt instance that we will use in stores and actions.

该文件所做的全部工作就是导出将在商店和操作中使用的Alt实例。

Create DataActions.js in the “actions” folder. This file will have all the logic for getting the data from the WordPress REST API endpoints. For talking to the API we’ll use axios. Include this in DataActions.js:

在“ actions”文件夹中创建DataActions.js 。 该文件将具有从WordPress REST API端点获取数据的所有逻辑。 为了与API对话,我们将使用axios 。 包括在DataActions.js

Don’t forget to replace the WordPress installation example URL with yours.

别忘了用您的WordPress替换安装示例URL。

Create DataStore.js in “stores” folder. This file will be listening to DataActions.js’ getSuccess() method that returns data from the WordPress API. It will then store and manipulate the data. Paste this in DataStore.js:

在“ stores”文件夹中创建DataStore.js 。 该文件将监听DataActions.js的getSuccess()方法,该方法从WordPress API返回数据。 然后它将存储和处理数据。 将此粘贴到DataStore.js

To get data from the WordPress API and make it available for the app you need to include DataActions.js in index.js and wrap the render function in DataActions.getPages(). The returned response will later be used to dynamically create routes:

要从WordPress API获取数据并将其提供给应用程序,您需要在index.js包含DataActions.js并将render函数包装在DataActions.getPages() 。 返回的响应稍后将用于动态创建路由:

Now every time the app gets initiated DataActions.getPages() calls the WordPress API endpoint and stores returned data in DataStore.js.

现在,每次应用启动时, DataActions.getPages()调用WordPress API终结点并将返回的数据存储在DataStore.js

To access it simply include the DataStore.js in any component and call the appropriate method. For example let’s get all the data inside the Home.js file and console.log it:

要访问它,只需在任何组件中包括DataStore.js并调用适当的方法。 例如,让我们获取Home.js文件中的所有数据并用console.log它:

After Webpack refreshes the page you should see the returned data object in the console:

Webpack刷新页面后,您应该在控制台中看到返回的数据对象:

Object {pages: Array[1], posts: Array[1]}

动态路线 (Dynamic Routes)

Right now there are no routes set in the app other than the index route. If you have a few pages created in WordPress backend, chances are you want them to be available for the front end. To dynamically add routes to React Router we need to add another method in index.js, let’s call it buildRoutes():

目前,除了索引路由外,应用程序中没有其他路由设置。 如果您在WordPress后端中创建了一些页面,则很可能希望它们可用于前端。 为了动态地向React Router添加路由,我们需要在index.js添加另一个方法,我们称之为buildRoutes()

Include {this.buildRoutes(response)} inside of React Router right after <Route path=”/” component={ Home } exact />. The method simply loops through all pages returned by the WordPress API and returns new routes. Notice how for each route it adds the “Home” component. This means that the “Home” component will be used for every route.

将< {this.buildRoutes(response)}放在React Router的<Route path=”/” component={ Home } exact 。 该方法仅循环遍历WordPress API返回的所有页面,并返回新的路由。 请注意,它如何为每个路由添加“主页”组件。 这意味着“本地”组件将用于每条路线。

Let’s say in WordPress you have a page with a slug “about. If you go to the route for that page “/about” it will load but you will still see the same “Hello World” message. In the case that you only need one template for every page, you can leave it as is and get page specific data by calling DataStore.getPageBySlug(slug) and providing the current page slug.

假设在WordPress中您有一个带有“ about ”字样的页面。 如果转到该页面“ / about”的路线,它将加载,但您仍然会看到相同的“ Hello World”消息。 如果每个页面仅需要一个模板,则可以通过调用DataStore.getPageBySlug(slug)并提供当前页面标签来保持原样并获取页面特定的数据。

In most cases, though, you would need to have multiple templates for different pages.

但是,在大多数情况下,您需要为不同的页面提供多个模板。

页面模板 (Page Templates)

In order to use page templates we need to let React know what template to use with any given page. We can use the page slug that gets returned by the API to map templates to different routes.

为了使用页面模板,我们需要让React知道在任何给定页面上使用什么模板。 我们可以使用API​​返回的页面信息来将模板映射到不同的路由。

Let’s assume we have two pages with slugs “home” and “about”. We need to create an object that maps page slugs to React component paths. Let’s name the object templates and include it in index.js:

假设我们有两个带有“ home”和“ about”子句的页面。 我们需要创建一个对象,该对象将页面插件映射到React组件路径。 让我们命名对象模板并将其包含在index.js

We also made updates to the buildRoutes() method to require the right component. Don’t forget to create the About.js component to map the “about” slug.

我们还对buildRoutes()方法进行了更新,以需要正确的组件。 不要忘记创建About.js组件以映射“ about”块。

In order to get page-specific data, all you need to do is call the DataStore.getPageBySlug(slug) method and provide the current page slug:

为了获取特定于页面的数据,您需要做的就是调用DataStore.getPageBySlug(slug)方法并提供当前页面的信息:

render() {    let page = DataStore.getPageBySlug(‘about’);
return (        <div>            <h1>{page.title.rendered}</h1>        </div>    );}

动态导航 (Dynamic Navigation)

Now we’re going to add a global navigation that will reflect all WordPress backend page links. First create a Header.js component in the “components” folder:

现在,我们将添加一个全局导航,该导航将反映所有WordPress后端页面链接。 首先在“ components”文件夹中创建一个Header.js组件:

We get all pages from WordPress using DataStore.getAllPages(), then we’re sorting them by “menu_order” with lodash and looping through them to spit out the React Router’s <Link />. Note that the homepage route is being excluded from the allPages array and included as a separate link.

我们使用DataStore.getAllPages()从WordPress获取所有页面,然后使用lodash按“ menu_order”对它们进行排序,并循环遍历它们以吐出React Router的<Link />。 请注意,主页路由已从allPages数组中排除,并作为单独的链接包含在内。

Include the Header.js component into index.js and you’ll see the dynamic nav included on every page:

Header.js组件包含到index.js ,您将在每个页面上看到动态导航:

高级自定义字段 (Advanced Custom Fields)

Most WordPress developers are familiar with Advanced Custom Fields plugin. It makes the WordPress CMS fully customizable and user friendly. Fortunately, it’s very easy to access ACF data by utilizing WordPress API.

大多数WordPress开发人员都熟悉Advanced Custom Fields插件。 它使WordPress CMS完全可自定义且用户友好。 幸运的是,利用WordPress API可以很容易地访问ACF数据。

To get ACF data from API endpoints we need to install another plugin called ACF to REST API. This will include an acf property in the object returned by the WordPress API. You can access the acf fields like so:

为了从API端点获取ACF数据,我们需要在REST API上安装另一个名为ACF的插件。 这将在WordPress API返回的对象中包含acf属性。 您可以像这样访问acf字段:

render() {    let page = DataStore.getPageBySlug(‘about’);    let acf = page.acf; // Advanced Custom Fields data
return (        <div>            <h1>{acf.yourCustomFieldName}</h1>        </div>    );}

下一步 (Next Steps)

All right, we’ve covered the most common use case for leveraging the WordPress CMS admin, along with a React front-end.

好了,我们已经介绍了利用WordPress CMS管理员以及React前端的最常见用例。

Some next steps might be to add styling for the project in Less or Sass. Or maybe extending the DataAction.js file by adding additional API endpoint calls to pull more data like comments, categories, and taxonomies.

下一步可能是在Less或Sass中为项目添加样式。 或者,也许可以通过添加其他API端点调用来扩展DataAction.js文件,以提取更多数据,例如注释,类别和分类法。

I strongly recommend checking out the official WordPress REST API handbook, where the API functionality is well documented. There you’ll find information about CRUD, pagination, authentication, querying, creating custom endpoints, and more. These resources will help extend what we’ve built here.

我强烈建议您查阅WordPress REST API官方手册 ,其中对API功能进行了详细记录。 在这里,您将找到有关CRUD,分页,身份验证,查询,创建自定义端点等的信息。 这些资源将有助于扩展我们在此处构建的内容。

by Andrey Pokrovskiy Senior Developer at Gigareef

作者: Andrey Pokrovskiy高级开发人员 Gigareef

If you got this far, you might be the kind of developer who would be a great fit at Gigareef. We are currently looking for talented developers to work on projects involving ReactJS/MEAN Stack/Handlebars/Node projects.

如果您走了这么远,那么您可能就是那种非常适合Gigareef的开发人员。 我们目前正在寻找有才华的开发人员来从事涉及ReactJS / MEAN Stack / Handlebars / Node项目的项目。

Send an email to jobs@gigareef.com and tell us a little bit about yourself.

发送电子邮件至jobs@gigareef.com,并向我们​​介绍一些有关您自己的信息。

Gigareef, where technology flourishes

技术蓬勃发展的 Gigareef

翻译自: https://www.freecodecamp.org/news/how-to-build-react-apps-on-top-of-the-wordpress-rest-api-bcc632808025/

react api

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值