[Node.js] Mock an API for Local Development in React with Mirage JS

Mirage JS lets you mock out production APIs directly alongside your frontend React code. You can tweak the data or force a network request to hang, so you can quickly design different states of your application. In this way Mirage lets you build every state of your UI regardless of the state of your production API.

Check out Mirage's React quickstart here.

// src/App.js
import React, { useState, useEffect } from "react"
import { Server } from "miragejs"

let server = new Server()
server.get("/api/users", { users: [{ id: 1, name: "Bob" }] })

export default function App() {
  let [users, setUsers] = useState([])

  useEffect(() => {
    fetch("/api/users")
      .then((res) => res.json())
      .then((json) => {
        setUsers(json.users)
      })
  }, [])

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

  

原文地址:https://www.cnblogs.com/Answer1215/p/12980879.html