JSON文件服务器不会提取

发布于 2025-01-28 23:09:06 字数 2687 浏览 3 评论 0原文

我创建了一个JSON文件,并且运行正常,但是它没有插入一个新项目,只能删除。下面遵循代码。我只是在模拟使用一些输入,删除和更新的服务器,与React 18.1.0和材料UI一起工作。 JSON数据文件“ SRC/DATA/DB.JSON”它从组件“ Notes”正确加载。 我需要在功能handlesubmit上插入一个新项目,该项目已在OnSubmit形式上插入。

Function to insert a new item, and after, go to the root page "/".

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [name, setName] = useState('')
    const [address, setAddress] = useState('')
    const [nameError, setNameError] = useState(false)
    const [addressError, setAddressError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setNameError(false)
        setAddressError(false)

        if(name == ''){
            setNameError(true)
        }

        if(address == ''){
            setAddressError(true)
        }

        if( name && address){
            fetch('http://localhost:8000/banks', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({name, address, status})
                .then(() =>  history.push('/')),
            })
           
        }
        
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar um novo Banco
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>

 Deleting is working correctly. Why insert doesn't work?
 
 export default function Notes(){
    const [ notes, setNotes ] = useState([]); 

    useEffect(() => {
        fetch('http://localhost:8000/banks')
        .then(res => res.json())
        .then(data => setNotes(data))
    }, []);

const handleDelete = async (id) => {
    await fetch('http://localhost:8000/banks/' + id, {
        method: 'DELETE'
    })
    const newNotes = notes.filter(note => note.id != id) ;
    setNotes(newNotes);
}

    return(
        <Container>
            <Grid container spacing={3}>
           {notes.map(note => (
               <Grid item key={note.id} xs={12} md={6} lg={4}>
                  <CardBanks note={ note } handleDelete={handleDelete}/>  {/*passing props note with element note */}
               </Grid>
           ))}
           </Grid>
        </Container>
    )
}

最好的问候,并提前感谢。

I created a Json file, and is running ok, but it doesn't insert a new item, only delete is working. Below follows the code. I'm just simulating a server with some input, delete and update, I'm working with React 18.1.0 and Material-ui.
The json data file "src/data/db.json" it loads properly from the component "Notes".
I need to insert a new item on the function handleSubmit, which is on form onSubmit.

Function to insert a new item, and after, go to the root page "/".

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [name, setName] = useState('')
    const [address, setAddress] = useState('')
    const [nameError, setNameError] = useState(false)
    const [addressError, setAddressError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setNameError(false)
        setAddressError(false)

        if(name == ''){
            setNameError(true)
        }

        if(address == ''){
            setAddressError(true)
        }

        if( name && address){
            fetch('http://localhost:8000/banks', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({name, address, status})
                .then(() =>  history.push('/')),
            })
           
        }
        
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar um novo Banco
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>

 Deleting is working correctly. Why insert doesn't work?
 
 export default function Notes(){
    const [ notes, setNotes ] = useState([]); 

    useEffect(() => {
        fetch('http://localhost:8000/banks')
        .then(res => res.json())
        .then(data => setNotes(data))
    }, []);

const handleDelete = async (id) => {
    await fetch('http://localhost:8000/banks/' + id, {
        method: 'DELETE'
    })
    const newNotes = notes.filter(note => note.id != id) ;
    setNotes(newNotes);
}

    return(
        <Container>
            <Grid container spacing={3}>
           {notes.map(note => (
               <Grid item key={note.id} xs={12} md={6} lg={4}>
                  <CardBanks note={ note } handleDelete={handleDelete}/>  {/*passing props note with element note */}
               </Grid>
           ))}
           </Grid>
        </Container>
    )
}

Best regards and thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭泣的笑容 2025-02-04 23:09:06

我使用此代码解决了此问题:。然后将其放置在函数内,因此应将其放置在括号的末尾,下一行。

import React, { useState } from 'react';
import { FormControlLabel, RadioGroup, Typography } from '@mui/material';
import { Button } from '@mui/material';
import { Container } from '@mui/material';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { makeStyles } from '@mui/styles';
import { TextField } from '@mui/material';
import { Radio } from '@mui/material';
import { FormLabel } from '@mui/material';
import { FormControl } from '@mui/material';
import { useHistory } from 'react-router-dom';
import '../Styles.css';
import { Box } from '@mui/material';


const useStyles = makeStyles(({
    
    field: {
        spacing: 4,
        display: "block",
    }
    
}));

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [title, setTitle] = useState('')
    const [details, setDetails] = useState('')
    const [titleError, setTitleError] = useState(false)
    const [detailsError, setDetailsError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setTitleError(false)
        setDetailsError(false)

        if(title == ''){
            setTitleError(true)
        }

        if(details == ''){
            setDetailsError(true)
        }

        if( title && details){
            fetch('http://localhost:8000/notes', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({ title, details, status })
            })
            .then(() =>  history.push('/'))
        }
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar uma nova  Tarefa - Post-It
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>

I solved this using this code: .then was placed inside the function, so it should be placed at the end of parenthesis, next line.

import React, { useState } from 'react';
import { FormControlLabel, RadioGroup, Typography } from '@mui/material';
import { Button } from '@mui/material';
import { Container } from '@mui/material';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';
import { makeStyles } from '@mui/styles';
import { TextField } from '@mui/material';
import { Radio } from '@mui/material';
import { FormLabel } from '@mui/material';
import { FormControl } from '@mui/material';
import { useHistory } from 'react-router-dom';
import '../Styles.css';
import { Box } from '@mui/material';


const useStyles = makeStyles(({
    
    field: {
        spacing: 4,
        display: "block",
    }
    
}));

export default function Bancos(){
    const classes = useStyles()
    const history = useHistory()
    const [title, setTitle] = useState('')
    const [details, setDetails] = useState('')
    const [titleError, setTitleError] = useState(false)
    const [detailsError, setDetailsError] = useState(false)
    const [status, setStatus] =useState('active')

    const handleSubmit = (e) => {
        e.preventDefault()
        setTitleError(false)
        setDetailsError(false)

        if(title == ''){
            setTitleError(true)
        }

        if(details == ''){
            setDetailsError(true)
        }

        if( title && details){
            fetch('http://localhost:8000/notes', {
                method: 'POST',
                headers: { "Content-type": "application/json" },
                body: JSON.stringify({ title, details, status })
            })
            .then(() =>  history.push('/'))
        }
    }

    return(
        <Container>
           <Typography  variant="h6" color="textSecondary" align="center" gutterBottom
            className="titleBank">
               Cadastrar uma nova  Tarefa - Post-It
           </Typography>

            <form noValidate autoComplete="off" onSubmit={handleSubmit}>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文