📜  如何在 ReactJS 中进行 crud 操作?

📅  最后修改于: 2022-05-13 01:56:13.929000             🧑  作者: Mango

如何在 ReactJS 中进行 crud 操作?

CRUD 代表创建、读取、更新和删除。在 ReactJS 中,一切都以组件的形式对齐,每个组件都有自己的方式和特性。

React js 是前端开发中最常用的 JavaScript 库之一。在 react-js 中拥有 CRUD 操作的基本功能非常重要。在本文中,我们不使用任何 JSON 服务器或 Axios 来执行 CRUD 操作。我们将使用一个简单的 JavaScript 对象来做到这一点。

要学习使用 ReactJS 和 NodeJS 进行 CRUD 操作,请参阅如何使用 Node.js 和 ReactJS 构建基本的 CRUD 应用程序?

  • 创建:创建帖子或添加表格行、将数据添加到网页或创建内容。
  • 读取:从网页读取或检索数据
  • 更新:更新或编辑网页中的现有内容
  • 删除:从网页中删除和删除条目或内容/帖子

在本文中,我们将学习添加用户的姓名和年龄,并在其中执行 CRUD 操作。

第 1 步:设置项目

确保您的计算机上安装了 node-js 以创建反应应用程序。输入这些命令来创建反应应用程序

npx create-react-app crud_app
or
yarn create react-app crud_app

重要安装后,在终端/cmd输入这些命令

cd crud_app
npm start or yarn start

这将启动应用程序

第 2 步:项目结构

您可以删除其他文件,如徽标和其他测试文件并将其删除。这里有 4 个组件中的文件,它们是源文件夹中此应用程序的核心。

  1. array.js -这个文件不是一个反应文件,而是一个简单的 JavaScript 对象文件(我们的临时数据源)。该对象有 3 个键值对 id、name 和 age。
  2. Create.js -此文件包含用于创建帖子或在应用程序中添加表格行的逻辑。
  3. Edit.js –此文件负责编辑现有条目。
  4. Home.js -该文件是一个读取文件,负责显示信息/数据。

第三步:安装依赖

首先下载这个依赖 -

DependencyInstallation commandUsing purpose
React-Bootstrap

npm install react-bootstrap bootstrap@5.1.3

or

yarn add react-bootstrap bootstrap@5.1.3

Bootstrap is a CSS framework that react-router will help us for focusing on functionality rather than on CSS.
React Router Dom

npm install react-router-dom

or

yarn add react-router-dom

We use react router dom for various packages and modules like routers for routing, useNavigations and etc.

现在,安装后,请在src文件夹中创建一个文件夹命名组件。然后制作4个js文件

Create.js
Edit.js
Home.js
array.js

第 4 步:组件文件 - 创建文件

array.js
// Javascript object named array with 3 key-values
const array = [
    {
        id:'1', 
        Name:'Shivansh',
        Age:'23'
    },
    {
        id:'2', 
        Name:'Simran',
        Age:'22'
    },
    {
        id:'3',
        Name:'Aakash',
        Age:'23'
    }
]
  
export default array


app.js
// important imports
import React from 'react'
import { BrowserRouter as Router,Route, Routes }
    from 'react-router-dom';
import './App.css';
import Create from './components/Create';
import Edit from './components/Edit';
import Home from './components/Home';
  
function App() {
  return (
    
                        }/>         }/>         }/>               
);    }    export default App;


Create.js
import React, { useState } from 'react' 
import { Button, Form } from 'react-bootstrap' 
import 'bootstrap/dist/css/bootstrap.min.css';
import array from './array';
import { v4 as uuid } from 'uuid';
import { Link, useNavigate } from 'react-router-dom';
  
function Create() {
  
    // Making usestate for setting and
    // fetching a value in jsx
    const [name, setname] = useState('');
    const [age, setage] = useState('');
  
    // Using useNavigation for redirecting to pages
    let history = useNavigate();
  
    // Function for creating a post/entry
    const handelSubmit = (e) =>{
        e.preventDefault();  // Prevent reload
  
        const ids = uuid() // Creating unique id
        let uni = ids.slice(0,8) // Slicing unique id
  
        // Fetching a value from usestate and 
        // pushing to javascript object
        let a = name, b=age
        array.push({id:uni,Name:a,Age:b})
  
  
       // Redirecting to home page after creation done
       history('/')
         
    }
  
  return (
    
        
     {/* Fetching a value from input textfirld     in a setname using usestate*/}         setname(e.target.value)}                    type="text"                   placeholder="Enter Name" required/>               {/* Fetching a value from input textfirld in      a setage using usestate*/}         setage(e.target.value)}                    type="text"                   placeholder="Age" required/>           {/* handing a onclick event in button for      firing a function */}         {/* Redirecting back to home page */}              
    
  ) }    export default Create


Home.js
import React from 'react'
import { Button,Table } from 'react-bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'; 
import array from './array'; 
import { Link, useNavigate } from 'react-router-dom';
  
function Home() {
  
  let history = useNavigate()
  
  // You may skip this part if you're
  // using react-context api or redux
  function setID(id,name,age){
    localStorage.setItem('id', id);
    localStorage.setItem('Name', name);
    localStorage.setItem('Age', age);
  }
  
  // Deleted function - functionality 
  // for deleting the entry
  function deleted(id){
      
    var index = array.map(function(e) { return e.id; }).indexOf(id);
  
    // deleting the entry with index
    array.splice(index,1)
  
    // We need to re-render the page for getting 
    // the results so redirect to same page.
    history('/')
  }
  
  return (
    
        
  
    
      
      
    
  
  
  
    {/* Mapping though every element in the array
    and showing the data in the form of table */}
    {array.map((item) => {
return(

      
      
        
      {/* getting theid,name, and age for storing these
          value in the jsx with onclick event */}
      
  
      {/* Using thr deleted function passing
       the id of an entry */}
      
    
)})}
  
NameAge
{item.Name}{item.Age}
   {/* Button for redirecting to create page for    insertion of values */}        
  ) }    export default Home


Edit.js
import React, { useEffect, useState } from 'react'
import { Button, Form } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import array from './array';
import { Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
  
  
function Edit() {
  
    // Here usestate has been used in order
    // to set and get values from the jsx
    const [name, setname] = useState('');
    const [age, setage] = useState('');
    const[id,setid] = useState('');
  
    // used for navigation with logic in javascript
    let history = useNavigate()
      
    // getting an index of an entry with an id
    var index = array.map(function(e) { return e.id; }).indexOf(id);
  
    // function for handling the edit and 
    // pushing changes of editing/updating
    const handelSubmit = (e) =>{
        e.preventDefault(); // preventing from reload
          
        let a = array[index] // getting an index of an array
  
        // putting the value from the input textfield and
        // replacing it from existing for updation
        a.Name = name
        a.Age = age
  
        // redirecting to main page
        history('/')
    }
  
  
    // Useeffect take care that page will be rendered only once
    useEffect(() => {
        setname(localStorage.getItem('Name'))
        setage(localStorage.getItem('Age'))
        setid(localStorage.getItem('id'))
    }, [])
      
  return (
    
        
               {/* setting a name from the input textfiled */}                               setname(e.target.value)}                                 type="text" placeholder="Enter Name" />                             {/* setting a age from the input textfiled */}                               setage(e.target.value)}                                type="text" placeholder="Age" />                             {/* Hadinling an onclick event running an edit logic */}                             {/* Redirecting to main page after editing */}                                                  
    
  ) }    export default Edit


app.js:该文件用于管理所有其他组件文件并提供到所有其他组件的路由。

应用程序.js

// important imports
import React from 'react'
import { BrowserRouter as Router,Route, Routes }
    from 'react-router-dom';
import './App.css';
import Create from './components/Create';
import Edit from './components/Edit';
import Home from './components/Home';
  
function App() {
  return (
    
                        }/>         }/>         }/>               
);    }    export default App;

第 5 步:创建组件

创建.js

import React, { useState } from 'react' 
import { Button, Form } from 'react-bootstrap' 
import 'bootstrap/dist/css/bootstrap.min.css';
import array from './array';
import { v4 as uuid } from 'uuid';
import { Link, useNavigate } from 'react-router-dom';
  
function Create() {
  
    // Making usestate for setting and
    // fetching a value in jsx
    const [name, setname] = useState('');
    const [age, setage] = useState('');
  
    // Using useNavigation for redirecting to pages
    let history = useNavigate();
  
    // Function for creating a post/entry
    const handelSubmit = (e) =>{
        e.preventDefault();  // Prevent reload
  
        const ids = uuid() // Creating unique id
        let uni = ids.slice(0,8) // Slicing unique id
  
        // Fetching a value from usestate and 
        // pushing to javascript object
        let a = name, b=age
        array.push({id:uni,Name:a,Age:b})
  
  
       // Redirecting to home page after creation done
       history('/')
         
    }
  
  return (
    
        
     {/* Fetching a value from input textfirld     in a setname using usestate*/}         setname(e.target.value)}                    type="text"                   placeholder="Enter Name" required/>               {/* Fetching a value from input textfirld in      a setage using usestate*/}         setage(e.target.value)}                    type="text"                   placeholder="Age" required/>           {/* handing a onclick event in button for      firing a function */}         {/* Redirecting back to home page */}              
    
  ) }    export default Create

输出:

主页.js

import React from 'react'
import { Button,Table } from 'react-bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'; 
import array from './array'; 
import { Link, useNavigate } from 'react-router-dom';
  
function Home() {
  
  let history = useNavigate()
  
  // You may skip this part if you're
  // using react-context api or redux
  function setID(id,name,age){
    localStorage.setItem('id', id);
    localStorage.setItem('Name', name);
    localStorage.setItem('Age', age);
  }
  
  // Deleted function - functionality 
  // for deleting the entry
  function deleted(id){
      
    var index = array.map(function(e) { return e.id; }).indexOf(id);
  
    // deleting the entry with index
    array.splice(index,1)
  
    // We need to re-render the page for getting 
    // the results so redirect to same page.
    history('/')
  }
  
  return (
    
        
  
    
      
      
    
  
  
  
    {/* Mapping though every element in the array
    and showing the data in the form of table */}
    {array.map((item) => {
return(

      
      
        
      {/* getting theid,name, and age for storing these
          value in the jsx with onclick event */}
      
  
      {/* Using thr deleted function passing
       the id of an entry */}
      
    
)})}
  
NameAge
{item.Name}{item.Age}
   {/* Button for redirecting to create page for    insertion of values */}        
  ) }    export default Home

在这里,我使用 localstorage 来存储一个值并在其他页面中使用这些值。例如,如果您使用 react-context-api 或 redux,则可以跳过此步骤。

输出:

编辑.js

import React, { useEffect, useState } from 'react'
import { Button, Form } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import array from './array';
import { Link} from 'react-router-dom';
import {useNavigate} from 'react-router-dom';
  
  
function Edit() {
  
    // Here usestate has been used in order
    // to set and get values from the jsx
    const [name, setname] = useState('');
    const [age, setage] = useState('');
    const[id,setid] = useState('');
  
    // used for navigation with logic in javascript
    let history = useNavigate()
      
    // getting an index of an entry with an id
    var index = array.map(function(e) { return e.id; }).indexOf(id);
  
    // function for handling the edit and 
    // pushing changes of editing/updating
    const handelSubmit = (e) =>{
        e.preventDefault(); // preventing from reload
          
        let a = array[index] // getting an index of an array
  
        // putting the value from the input textfield and
        // replacing it from existing for updation
        a.Name = name
        a.Age = age
  
        // redirecting to main page
        history('/')
    }
  
  
    // Useeffect take care that page will be rendered only once
    useEffect(() => {
        setname(localStorage.getItem('Name'))
        setage(localStorage.getItem('Age'))
        setid(localStorage.getItem('id'))
    }, [])
      
  return (
    
        
               {/* setting a name from the input textfiled */}                               setname(e.target.value)}                                 type="text" placeholder="Enter Name" />                             {/* setting a age from the input textfiled */}                               setage(e.target.value)}                                type="text" placeholder="Age" />                             {/* Hadinling an onclick event running an edit logic */}                             {/* Redirecting to main page after editing */}                                                  
    
  ) }    export default Edit

输出: