使用相同的格式更新添加的数据| React.js

时间:2019-06-27 19:34:05

标签: javascript reactjs

在这里,我正在尝试执行CRUD流程。现在,我可以添加,删除和显示数据。但是,我无法更新现有数据。我想更新或编辑现有数据。我尝试了不同的方法来实现这一目标,但没有任何效果。 请检查下面的代码,让我知道,我该怎么做。

应用组件:

import React, { Component } from 'react';
import { withStyles, Grid } from '@material-ui/core';
import styles from './Style'
import Form from './Form';
import DataList from './DataList';
import Header from '../../components/Header';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            Datas: [
                {id: 0, Name: 'Tony Stark', Occupation: 'Iron Man', Details: 'SuperHero, PlayBoy, Philatherophist' },
                {id: 1, Name: 'Steve Rogers', Occupation: 'Captain America', Details: 'Captain, Soldier, SuperHero' },
                {id: 2, Name: 'Thor', Occupation: 'God of Thunder', Details: 'SuperHero, God, King' },
            ],
            Name: "",
            Occupation: "",
            Details: "",
        }
    }

    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value       
         })
    }

    handleClick = (e, data) => {
        e.preventDefault();
        //data.id = Math.random()
        let Datas = [...this.state.Datas, {id: Math.random(), Name: this.state.Name, Occupation: this.state.Occupation, Details: this.state.Details}];
        this.setState({
            Datas
        })
        this.reset()
    }

    handleDelete = (id) => {
        const Datas = this.state.Datas.filter(data=>{
            return data.id !== id
        });
        this.setState({
            Datas
        })
    };

    handleUpdate = (e, id) => {

        const index = this.state.Datas.findIndex((data)=>{
            return data.id === id
        });

        const data = Object.assign({}, this.state.Datas[index])
        data.Name = e.target.value
        data.Occupation = e.target.value
        data.Details = e.target.value

        const Datas = Object.assign([], this.state.Datas);
        Datas[index]= data;
        this.setState({
            Datas
        })
    }

    reset = () => {
        this.setState({
           Name: "",
           Occupation: "",
           Details: ""
        })
    }
    render() {
        const { classes } = this.props
        const { Name, Occupation, Details, Datas } = this.state
        return (
            <div>
                <Header />
                <Grid container >
                    <Grid item xs = {6}>
                        <div className={classes.cover}>
                            <Form 
                                handleChange={this.handleChange} 
                                handleClick={this.handleClick} 
                                Name={Name} 
                                Occupation={Occupation} 
                                Details={Details} 
                            />
                        </div>
                    </Grid>
                    <Grid item xs = {6}>
                        <div className={classes.cover}>
                            <DataList 
                                datas={Datas}
                                handleDelete={this.handleDelete}
                                handleUpdate={this.handleUpdate}
                            />
                        </div>
                    </Grid>
                </Grid>

            </div>
        )
    }
}

export default withStyles(styles)(App)

表单组件

import React from 'react';
import { withStyles, TextField, Button } from '@material-ui/core';
import styles from './Style'


const Form = (props) => {
    const { classes, Name, Occupation, Details } = props
    return (
        <div>
            <form >
                <TextField
                    type="text"
                    name="Name"
                    label="Name"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Name}
                />
                <TextField
                    type="text"
                    name="Occupation"
                    label="Occupation"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Occupation}
                />
                <TextField
                    type="text"
                    name="Details"
                    label="Details"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Details}
                />
                <Button variant="outlined" onClick={props.handleClick} type="submit" className = {classes.button}>Submit</Button>
            </form>
        </div>
    )
}

export default withStyles(styles)(Form)

DataList组件

import React from 'react';
import { withStyles, Card, CardContent, Typography, IconButton} from '@material-ui/core';
import Delete from '@material-ui/icons/DeleteOutlined'
import styles from './Style'

const DataList = (props) => {
    const { datas, classes } = props
    return (
        <div>
            {
            datas.map((data)=> {
                return (
                    <Card key={data.id} className={classes.card} onClick={(e) => props.handleUpdate(e, data.id)} elevation={1}>
                        <CardContent>
                            <IconButton aria-label="Delete" className={classes.delete} onClick={()=>props.handleDelete(data.id)}>
                                <Delete />
                            </IconButton>
                            <Typography variant="h4" className={classes.name}>
                                {data.Name}
                            </Typography>
                            <Typography variant="h6" className={classes.body}> 
                                {data.Occupation}
                            </Typography>
                            <Typography variant="body1" className={classes.details}>
                                {data.Details}
                            </Typography>
                        </CardContent>
                    </Card>
                )
            })
            }
        </div>
    )
}

export default withStyles(styles)(DataList)

1 个答案:

答案 0 :(得分:1)

应为id,然后为event(交换参数)。您期望绑定函数将事件作为第一个参数接收,而它将是id。另外,由于您已将handleupdate定义为App中的箭头函数,因此不需要将函数绑定到this(BTW,它将是未定义的)。

 handleUpdate = (id, event) => {
   .
   .
   .        
 }

OR

您只需做

<Card key={data.id} className={classes.card} 
      onClick={ e => { 
        props.handleUpdate(e, data.id) 
      }} 
      elevation={1}
>

------------更新-----------

这是解决方案-

您可以在状态下使用Id来跟踪当前正在编辑的对象,并可以使用Editing来跟踪表单处于编辑状态以进行更新。然后,Editing状态用于为edtis而不是提交呈现保存按钮。

App.js

import React, { Component } from "react";
import { withStyles, Grid } from "@material-ui/core";
import styles from "./Style";
import Form from "./Form";
import DataList from "./DataList";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Datas: [
                {
                    id: 0,
                    Name: "Tony Stark",
                    Occupation: "Iron Man",
                    Details: "SuperHero, PlayBoy, Philatherophist"
                },
                {
                    id: 1,
                    Name: "Steve Rogers",
                    Occupation: "Captain America",
                    Details: "Captain, Soldier, SuperHero"
                },
                {
                    id: 2,
                    Name: "Thor",
                    Occupation: "God of Thunder",
                    Details: "SuperHero, God, King"
                }
            ],
            Id: "",
            Name: "",
            Occupation: "",
            Details: "",
            IsEditing: false
        };
    }

    handleChange = e => {
        this.setState({
            [e.target.name]: e.target.value
        });
    };

    handleClick = (e, data) => {
        e.preventDefault();
        //data.id = Math.random()
        let Datas = [
            ...this.state.Datas,
            {
                id: Math.random(),
                Name: this.state.Name,
                Occupation: this.state.Occupation,
                Details: this.state.Details
            }
        ];
        this.setState({
            Datas
        });
        this.reset();
    };

    handleDelete = id => {
        const Datas = this.state.Datas.filter(data => {
            return data.id !== id;
        });
        this.setState({
            Datas
        });
    };

    handleUpdate = (e, id) => {
        const index = this.state.Datas.findIndex(data => {
            return data.id === id;
        });

        const data = Object.assign({}, this.state.Datas[index]);
        this.setState({
            Id: data.id,
            Name: data.Name,
            Occupation: data.Occupation,
            Details: data.Details,
            IsEditing: true
        });
    };

    saveUpdate = id => {
        const newData = this.state.Datas.map(d => {
            console.log(id, d.id);
            if (d.id === id) {
                return {
                    Name: this.state.Name,
                    Occupation: this.state.Occupation,
                    Details: this.state.Details
                };
            }
            return d;
        });

        this.setState(
            {
                Datas: newData,
                IsEditing: false
            },
            () => {
                this.reset();
            }
        );
    };

    reset = () => {
        this.setState({
            Id: "",
            Name: "",
            Occupation: "",
            Details: ""
        });
    };
    render() {
        const { classes } = this.props;
        const { Id, Name, Occupation, Details, Datas, IsEditing } = this.state;
        return (
            <div>
                <Grid container>
                    <Grid item xs={6}>
                        <div className={classes.cover}>
                            <Form
                                handleChange={this.handleChange}
                                handleClick={this.handleClick}
                                saveUpdate={this.saveUpdate}
                                Id={Id}
                                Name={Name}
                                Occupation={Occupation}
                                Details={Details}
                                Editing={IsEditing}
                            />
                        </div>
                    </Grid>
                    <Grid item xs={6}>
                        <div className={classes.cover}>
                            <DataList
                                datas={Datas}
                                handleDelete={this.handleDelete}
                                handleUpdate={this.handleUpdate}
                            />
                        </div>
                    </Grid>
                </Grid>
            </div>
        );
    }
}

export default withStyles(styles)(App);

Form.js

import React from "react";
import { withStyles, TextField, Button } from "@material-ui/core";
import styles from "./Style";

const Form = props => {
    const { Id, classes, Name, Occupation, Details, Editing } = props;
    return (
        <div>
            <form>
                <TextField
                    type="text"
                    name="Name"
                    label="Name"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Name}
                />
                <TextField
                    type="text"
                    name="Occupation"
                    label="Occupation"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Occupation}
                />
                <TextField
                    type="text"
                    name="Details"
                    label="Details"
                    className={classes.textField}
                    onChange={props.handleChange}
                    value={Details}
                />
                {Editing ? (
                    <Button
                        variant="outlined"
                        onClick={e => {
                            e.preventDefault();
                            props.saveUpdate(Id);
                        }}
                        type="button"
                        className={classes.button}
                    >
                        Update
                    </Button>
                ) : (
                    <Button
                        variant="outlined"
                        onClick={props.handleClick}
                        type="submit"
                        className={classes.button}
                    >
                        Submit
                    </Button>
                )}
            </form>
        </div>
    );
};

export default withStyles(styles)(Form);