📅  最后修改于: 2023-12-03 15:22:22.997000             🧑  作者: Mango
ReactJS 是一个用于构建用户界面的 JavaScript 函数库。它可以与许多不同的后端技术和框架一起使用。在本教程中,我们将介绍如何使用后端和 Docker 创建一个 ReactJS 应用程序。
在开始之前,您需要安装并了解以下技术:
首先,我们将创建一个简单的 ReactJS 应用程序。为此,请按照以下步骤操作:
mkdir react-app
。npx create-react-app app
,其中“app”是您将为应用程序选择的名称。cd app
。npm start
。运行完上述命令后,将会看到如下内容:
Compiled successfully!
You can now view app in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.1.141:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
现在,您可以在浏览器中访问 http://localhost:3000/
来查看您的 ReactJS 应用程序。
接下来,我们将添加一个后端,以便我们可以获取来自后端的数据并将其用于 ReactJS 应用程序中。
mkdir server
。cd server
。npm init
。npm install express
。在“app.js”文件中,添加以下代码:
const express = require('express');
const app = express();
app.get('/hello', (_, res) => {
res.send('Hello World!');
});
app.listen(3001, () => {
console.log('Server running on port 3001');
});
这个代码会起一个简单的服务器,它会监听 3001 端口并发送字符串 "Hello World!"。
npm start
。运行完上述命令后,您将看到以下内容:
> server@1.0.0 start /Users/maket/Projects/ReactJS/bookstore/server
> node app.js
Server running on port 3001
现在,您可以在浏览器中访问 http://localhost:3001/hello
来测试服务器是否正在运行。
现在,我们将修改 ReactJS 应用程序代码,以便从后端获取数据。
import axios from 'axios';
。Axios 是一个流行的 JavaScript 库,用于处理 HTTP 请求。render() {
return (
<div className="App">
<p>{this.state.data}</p>
</div>
);
}
这将在页面上显示一个引用 ReactJS 状态中存储的数据的段落元素。
async fetchData() {
const response = await axios.get('http://localhost:3001/hello');
this.setState({data: response.data});
}
componentDidMount() {
this.fetchData();
}
fetchData
方法使用 Axios 发送 HTTP GET 请求,并在成功时将响应保存在 ReactJS 状态中。componentDidMount
方法在组件加载时自动调用 fetchData
方法。
this.state = {
data: '',
};
这将初始化 ReactJS 状态中的数据为空字符串。
npm start
。现在,您的 ReactJS 应用程序将从后端请求数据,并在加载时在页面上显示。
最后,我们将使用 Docker 将我们的应用程序部署到容器中。
在 Dockerfile 中添加以下内容:
FROM node:12-alpine
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]
这个 Dockerfile 指定我们的基础映像,工作目录,将应用程序复制到容器中并在其中运行“npm install”。
docker build -t my-react-app .
此命令将使用您的 Dockerfile 构建一个名为“my-react-app”映像。请注意,必须在“my-react-app”后面有一点。
docker run -p 3000:3000 -p 3001:3001 my-react-app
此命令将启动名为“my-react-app”的容器,并使用“-p”标志将本地端口映射到容器内部的端口。
现在,您的 ReactJS 应用程序已在 Docker 容器中运行,并且可以访问后端的数据。
在本教程中,我们介绍了如何使用后端和 Docker 创建一个 ReactJS 应用程序。我们创建了一个简单的 ReactJS 应用程序并添加了一个后端来提供数据。我们还将应用程序部署到 Docker 容器中以供使用。现在,您可以在自己的项目中使用这些技术来创建可扩展的、可靠的 ReactJS 应用程序。