1.打包
1.1.执行build命令
npm run build
执行完成之后, 在会多出一个build文件夹
1.2.执行
sudo npm install -g serve
serve -s build -p 8000
其中, -p后面跟的是端口号
这个时候,在浏览器上输入: http://localhost:8000
, 即可.
2.使用json-server模拟数据
Tips
: 相当于启动了一个service,提供客户端获取模拟的数据
2.1.安装json-server
npm install json-server
在packges.json里面出现如下:
2.2.设置server指令
这个时候需要在下面的scripts中,新增如下:
"server": "json-server --watch db.json --port 5000"
Tips
:
- 这个里面的db.json文件,是自定义的
- –port, 是json-server端口的意思
2.3.启动json-server
npm run server
这个时候, 会自动在项目目录下,新增一个db.json文件,该文件名称为2.2中的文件名,如下图:
这个时候,将模拟的数据
,放在这个db.json里面, 即可!
{
"tests": [
{
id: 1,
value: 'aaa'
},
{
id: 2,
value: 'bbb'
}
]
}
同时,在浏览器上,输入http://localhost:5000/tests
,即可获取上面的数据
2.4.json-server的使用
初始化获取数据: 使用useEffect
import { useState, useEffect } from "react"
const [tests, setTests] = useState([]);
// 初始化获取数据
useEffect(() => {
const getTests = async () => {
const testFromServer = await fetchTests();
setTests(testFromServer);
}
getTests();
}, []);
const fetchTests = async () => {// 在调用的时候,记得加上async
const res = await fetch('http://localhost:5000/tests');// 记得加上await
const data = await res.json();// 记得加上await
return data;
}
3.Fetch获取数据
3.1.get请求
import { useState, useEffect } from "react"
const [tests, setTests] = useState([]);
useEffect(() => {
const getTests = async () => {
const testFromServer = await fetchTests();
setTests(testFromServer);
}
getTests();
}, []);
//获取全部数据
const fetchTests = async () => {// 在调用的时候,记得加上async
const res = await fetch('http://localhost:5000/tests');// 记得加上await
const data = await res.json();// 记得加上await
return data;
}
// 根据ID获取
const fetchTest = async (id) => {
const res = await fetch(`http://localhost:5000/tests/${id}`);
const data = await res.json();
return data;
}
3.2.delete请求
import { useState } from "react"
const [tests, setTests] = useState([]);
const deleteTest = async (id) => {// 在调用的时候,记得加上async
await fetch(`http://localhost:5000/tests/${id}`, {method: 'DELETE'});// 记得加上await,方法使用DELETE
setTests(tests.filter((test)=>test.id !== id));
}
3.3.post请求
import { useState } from "react"
const [tests, setTests] = useState([]);
// 新增请求
const addTest = async (test) => {
const res = await fetch(`http://localhost:5000/tests`, {
method:'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(test)
})
const data = await res.json();
console.log(data)
setTests([...tests, data]);
}
3.3.put请求(更新)
import { useState } from "react"
const [tests, setTests] = useState([]);
// 根据ID查询
const fetchTest = async (id) => {
const res = await fetch(`http://localhost:5000/tests/${id}`);
const data = await res.json();
return data;
}
// 更新数据
const updateTest = async (id, value) => {
const oneTest = await fetchTest(id);
const updateTest = {...oneTest, value: value}
const res = await fetch(`http://localhost:5000/tasks/${id}`,{
method:'PUT',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(updateTest)
});
const data = await res.json();
setTests(tests.map((test)=> test.id === id ? {...test, value: data.value} : test));
}