How to quickly mock a backend API

Step 1: Create a folder to store your data

data:

{
    
    
  "todos": [
    {
    
     "id": 1, "text": "学习html44", "done": false },
    {
    
     "id": 2, "text": "学习css", "done": true },
    {
    
     "id": 3, "text": "学习javascript", "done": false }
  ]
}

data.json

image.png

Step 2: Use json-server to quickly simulate a backend API without actually building a complete backend server. This allows for easy development, testing, and demos without relying on real backend services.

npx json-server ./data.json --port 8080

  • npx: is a tool for running locally installed npm packages.
  • json-server: is a tool for creating RESTful APIs using JSON files as data sources.
  • ./data.json: is the path and file name of the specified JSON file, which will be provided to json-server as a data source.
  • --port 8080: is to specify the port number of the server as 8080, so that json-server will run on this port.

image.png

Step 3: Install axios

image.png

Step Four: Use

  import axios from "axios";

  const loadData = async () => {
    
    
      const res = await axios.get("http://localhost:8080/todos");
      console.log(res);
    };
    loadData();

image.png

Run successfully display

image.png

Practical application scenarios:

image.png

image.png

code:

// 导入
import {
    
     useState, useEffect } from "react";

import "./App.scss";
import axios from "axios";

// 子组件
const Module = ({
     
      id, done, text, onToggle, onDelData }) => {
    
    
  return (
    <div>
      <span className={
    
    done ? "" : "text"} onClick={
    
    () => onToggle(id, !done)}>
        -- {
    
    text} --
      </span>
      {
    
    /* 点击后子组件调用父组件函数,将 id 回传给父组件 */}
      <button onClick={
    
    () => onDelData(id)}>删除</button>
    </div>
  );
};

// 父组件
const App = () => {
    
    
  // 状态
  const [defaultTodoData, setDefaultTodo] = useState([]);

  // 发请求
  // 注意:不要直接在 useEffect 后边加 async ,因为它是同步的,不用在加了
  // 不是所有的请求都是在 useEffect 中发送,它只处理跟组件挂载、更新、卸载相关的请求代码
  // 比如事件处理程序:处理点击等用户操作时的请求代码
  useEffect(() => {
    
    
    const loadData = async () => {
    
    
      const res = await axios.get("http://localhost:8080/todos");
      setDefaultTodo(res.data);
      console.log(res.data);
    };
    loadData();
  }, []);

  // 修改文字状态
  const onToggle = async (id, done) => {
    
    
    setDefaultTodo(
      defaultTodoData.map((item) => {
    
    
        if (item.id === id) return {
    
     ...item, done: !item.done };
        return item;
      })
    );

    // 发请求,更新数据
    await axios.patch(`http://localhost:8080/todos/${
      
      id}`, {
    
     done });
  };

  // 删除
  const onDelData = (xId) => {
    
    
    const dataId = defaultTodoData.filter((item) => item.id !== parseInt(xId));
    console.log(xId, "点击了删除", dataId);
    setDefaultTodo(dataId);
  };

  return (
    <div>
      <p>xxx </p>
      {
    
    defaultTodoData.map((item) => {
    
    
        // key 可以直接用
        // return <Module key={item.id} done={item.done} text={item.text}></Module>;

        // {...item} 解构写法,简化开发
        // onToggle 给子组件调用的函数
        return (
          <Module
            key={
    
    item.id}
            {
    
    ...item}
            onToggle={
    
    onToggle}
            onDelData={
    
    onDelData}
          ></Module>
        );
      })}
    </div>
  );
};

export default App;

Guess you like

Origin blog.csdn.net/wbskb/article/details/131994704