json-server 实现数据 mock
实现步骤:
1. 在项目中安装 json-server
npm install -D json-server
2. 准备一个 json 文件
server/data.json
{
"posts": [
{ "id": "1", "title": "a title", "views": 100 },
{ "id": "2", "title": "another title", "views": 200 }
],
"comments": [
{ "id": "1", "text": "a comment about post 1", "postId": "1" },
{ "id": "2", "text": "another comment about post 1", "postId": "1" }
],
"profile": {
"name": "typicode"
}
}
3. 添加启动命令
"scripts":{
"server": "json-server ./server/data.json --port 8888"
}
4. 访问接口进行测试
npm run serve
const [commentList, setCommentList] = useState([]);
useEffect(() => {
async function getList() {
const res = await axios.get("http://localhost:8888");
setCommentList(res.data);
}
getList();
}, []);