iT邦幫忙

2022 iThome 鐵人賽

DAY 30
0
Modern Web

React應用記錄誌系列 第 30

Day30 MERN Stack -6 Frontend React實作

  • 分享至 

  • xImage
  •  

完成前後端應用程式後需兩個服務器端口一致才能運行,前端react預設運行的端口port為3000,如果在backend設置的服務器端口port是4000,要解決兩個不同的服務器端口,可以在前端的package.js最上面添加("proxy": "http://localhost:4000 "),設置開發服務器地址。

"proxy":"http://localhost:4000",
  "name": "frontend",
  "version": "0.1.0",

React 實作

App.js

import {BrowserRouter,Routes ,Route} from 'react-router-dom'
import Home from './Home'
import Nav from './Nav';

function App() {
  return (
    <div className="App">
    <BrowserRouter>
      <Nav />
      <div className="home">
        <Routes>
           <Route
              path="/" 
              element={<Home />}
              />
        </Routes>
      </div>
    </BrowserRouter>
      
    </div>
  );
}

export default App;

Nav.js

import { Link } from 'react-router-dom'

const Nav = () =>{
    return (
      <header>
        <div className="navber">
         <Link to="/">
            <h1>Users Information</h1>
         </Link>
        </div>
      </header>
    )
}
export default Nav

Home.js

import { useEffect,useState } from "react"
import UserDetails from '../component/UserDetails'
import UserForm from "../component/UserForm"

const Home = () =>{
    const [users,setUsers] = useState(null)
    useEffect(()=>{
        const fetchUsers = async () =>{
            const response = await fetch('/api/users')
            const json = await response.json()

            if (response. success){
              setUsers(json)
            }
        }

        fetchUsers()
    },[])

    return (
        <div className="container">
            <div className="users">
                {users && users.map(user)=>(
                    <UserDetails key={user._id} user={user} />
                ))}
            </div>
            <UserForm />
        </div>
    )
}

export default Home

UserDetails.js

const UserDetails = ({user})=>{

  return(
    <div className="user">
        <h4>name:{usert.title}</h4>
        <p>Load: {user.load}</p>
     </div>
  )
}
export default UserDetails

UserForm.js


import { useState } from "react"

const UserForm = () => {

   const [title, setTitle] = useState('')
   const [load, setLoad] = useState('')
   const [error, setError] = useState(null)
   
   const handleSubmit = async (e) => {
     e.preventDefault()
     
     const user = {title, load }
     const response = await fetch('/api/users', {
        method: 'POST',
        body: JSON.stringify(user),
        headers: {
            'Content-Type':'application/json'  
        }
     })
      const json = await response.json()
      
      if (!response. success){
        setError(json.error)
      }
      if (response. success){
        setError(null)
        setTitle('')
        setLoad('')
     }

   }

 return(
      <form  className="add"  onSubmit={handleSubmit}>
        <h3>Add a New User</h3>

        <label>User name:</label>
        <input
         type="text"
         onChange={(e)=>setTitle(e.target.value)}
         value={title}      
          />

        <label>Load:</label>
        <input
         type="number"
         onChange={(e)=>setLoad(e.target.value)}
         value={load}      
          />
               
          <button>Add User</button>
          {error && <div className="error">{error}</div>}
      </form>

    )
}

export default UserForm

上一篇
Day29 MERN Stack -5 RESTful API
下一篇
在Windows 安裝wsl 出現error: 0x80370102,如何修復錯誤
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言