0

У менять есть таблица и форма. Я вывожу данные с сервера и хочу добавить новые данные с запросом на сервер. Однако у меня проблема с правильной записью в json введенных данных. Программа почему-то читает только последнее поле для ввода и отправляет только последнее введенное значение. В моем коде закомментированная часть "[data]: ..." отправляет на сервер пустые значения(не undefinded). Подскажите пожалуйста в чем проблема. Ниже привожу пример данных json, Form.js, Table.js, App.js

[
{
_id: "600d76c4ae66af078a510ce1",
data: {
name: "Misha",
email: "tett",
age: "22"
},
__v: 0
}
]
import React, {Component} from 'react';

class Form extends Component {
    initialState = {
        __v: '',
        _id: '',
        data: {
            name: '',
            email: '',
            age: '',
        },
    }
    state = this.initialState;

    handleChange = event => {
        const { name, value } = event.target;

        this.setState({
            data: {
                [name] : value,
            }
            // [data]: {
            //     [name] : value,
            // }
        });
    }

    submitForm = async (event) => {
        event.preventDefault();
        this.props.handleSubmit(this.state);
        this.setState(this.initialState);

        const data = {
            data: {
                name: this.state.data.name,
                email: this.state.data.email,
                age: this.state.data.age,
            }
        };

        await fetch('http://178.128.196.163:3000/api/records', {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
            .then(() => {console.log(data)});
    }

    render() {
        const {name, email, age} = this.state;

        return(
            <form>
                <label htmlFor='name'>Name</label>
                <input
                    type='text'
                    name='name'
                    id='name'
                    value={name}
                    onChange={this.handleChange} />
                <label htmlFor='email'>Email</label>
                <input
                    type='text'
                    name='email'
                    id='email'
                    value={email}
                    onChange={this.handleChange} />
                <label htmlFor='age'>Age</label>
                <input
                    type='text'
                    name='age'
                    id='age'
                    value={age}
                    onChange={this.handleChange} />
                <input type='button' value='Submit' onClick={this.submitForm} />
            </form>
        )
    }
}
export default Form;
import React, {Component} from 'react';

const TableHeader = () => {
    return (
        <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Age</th>
            <th>Remove</th>
        </tr>
        </thead>
    )
}

const TableBody = (props) => {
    const rows = props.characterData.map((row, _id) => {
            return (
                <tr key={row._id}>
                    <td>{row._id}</td>
                    <td>{row._id}</td>
                    <td>{row._id}</td>
                    <td>
                        <button onClick={() => props.removeCharacter(row._id)}>Delete</button>
                    </td>
                </tr>
            )
        })
        return <tbody>{rows}</tbody>

}

const Table = (props) => {
    const {characterData, removeCharacter} = props;

    return (
        <table>
            <TableHeader />
            <TableBody characterData={characterData} removeCharacter={removeCharacter} />
        </table>
    )
}
export default Table;
import React, { Component } from 'react';
import './App.css';
import Table from './Table';
import Form from './Form'

class App extends Component {
    state = {
        characters: [],
    }

    componentDidMount() {
        this.getPeople()
    }

    getPeople() {
        fetch("http://178.128.196.163:3000/api/records")
            .then((result) => result.json())
            .then((result) => this.setState({characters: result,}))
            .catch(error => console.log(error));
    }

    handleSubmit = (character) => {
        this.setState({characters: [...this.state.characters, character]})
    }

    removeCharacter = async (_id) => {
        const {characters} = this.state;

        await fetch('http://178.128.196.163:3000/api/records/' + _id, {
            method: 'DELETE',
        })
            .then((result) => {
                return result.json();
            })
            .catch((error) => console.log(error))

        this.setState({
            characters: characters.filter((character, i) => {
                return i != _id;
            })
        })



    }

    render() {
        const {characters} = this.state;
        return (
            <div className='container'>
                <Table characterData={characters} removeCharacter={this.removeCharacter} />
                <Form handleSubmit={this.handleSubmit} />
            </div>
        )
    }
}

export default App;

1 ответ 1

1
this.setState({
   data: {
     [name] : value,
   }
});
this.setState(state => ({
   data: {
     ...state.data,
     [name]: value,
   }
}));
1
  • Спасибо большое, проблема решена! 27 янв 2021 в 15:23

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.