简体   繁体   English

从API更新时如何将参数从DataTable传递到Form?

[英]How to pass parameters from DataTable to Form on update from API?

I would like to update a row in React. 我想在React中更新一行。

I've got a data table that gets all of the data from an API, it works well. 我有一个数据表,可以从API获取所有数据,它运作良好。 When I click on update, the function redirects me to the form page and prints on console the ID that I chose. 当我单击更新时,该功能将我重定向到表单页面,并在控制台上打印我选择的ID。

UPDATE WORKS 更新工作

class PromoCatalog extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            promos: [],
            message: null
        };
        this.updatePromoClicked = this.updatePromoClicked.bind(this);
        this.refreshPromo = this.refreshPromo.bind(this);
    }

    componentDidMount() { //React defines a component lifecycle
        this.refreshPromo();
    }

    refreshPromo() {
        PromoCatalogService.retrieveAllPromo(PRIZES)//this would make the call to the REST API.
            .then(
                response => {
                    console.log(response);
                    this.setState({promos: response.data.shopping})
                }
            )
    }

    PromoOffClicked(id) {
        PromoCatalogService.promoOff(PRIZES, id)
            .then(
                response => {
                    console.log(response);
                    this.setState({message: `Promo ${id} OFF  Successful`});
                    this.refreshPromo();
                }
            )

    }

    updatePromoClicked(id, ijCod, title, description) {
        console.log('clicked id ' + id);

        this.props.history.push({
            pathname: '/admin/form_promo/'+ id,
            state: {'selectedId': id,
                'selectedIjCod': ijCod,
                'selectedTitle': title,
                'selectedDescription': description}
        })
    }

    addCourseClicked() {
        this.props.history.push(`/admin/form_promo/-1`);
    }


    render() {
        let promos = this.state.promos.map((item) => ({
            promoId: item.promoId,
            ijCod: item.ijCod,
            title: item.title,
            description: item.description,
            delete: <MDBBtn outline color="danger"
                            onClick={() => this.PromoOffClicked(item.promoId)}>OFF</MDBBtn>,
            update: <MDBBtn outline color="info"
                            onClick={() => this.updatePromoClicked(item.promoId, item.ijCod, item.title, item.description)}>Update</MDBBtn>         
        }));
        const data = {
            columns: [
                {
                    label: 'Id',
                    field: 'promoId',
                    sort: 'asc',
                    width: 150
                },
                {
                    label: 'Ij Cod',
                    field: 'ijCod',
                    sort: 'asc',
                    width: 270
                },
                {
                    label: 'Title',
                    field: 'title',
                    sort: 'asc',
                    width: 200
                },
                {
                    label: 'Description',
                    field: 'description',
                    sort: 'asc',
                    width: 270
                },
                {
                    label: 'Delete',
                    field: 'delete',
                    width: 100
                },
                {
                    label: 'Update',
                    field: 'update',
                    width: 100
                }
            ],
            rows: promos
        };

        return (
            <>
                <PanelHeader size="sm"/>
                <div className="content">
                    <Row>
                        <Col xs={12}>
                            <Card>
                                <CardHeader>
                                    <CardTitle tag="h4">Promo Catalog</CardTitle>
                                </CardHeader>
                                <CardBody>
                                    <MDBDataTable
                                        striped
                                        bordered
                                        small
                                        data={data}
                                    />
                                </CardBody>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </>
        );
    }
}

export default PromoCatalog

Here you can see my Update Page: 在这里您可以看到我的更新页面:

class UpdatePromo extends React.Component {

    emptyItem = {
        promoId: '',
        ijCod: '',
        title: '',
        description: ''
    };

    constructor(props) {
        super(props);
        this.state = {
            item: this.emptyItem
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentDidMount() {
        console.log('ID in UpdatePromo.jsx ', this.props.location.state.selectedIjCod);
        if (this.props.location.state.selectedId === -1) {
            this.props.history.push(`/admin/form_promo/-1`);
        }
        PromoCatalogService.filterById(PRIZES, this.props.location.state.selectedId)
            .then(response => this.setState({
                title: response.data.selectedTitle,
                description: response.data.selectedDescription
            }))
    }

    handleChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;
        let item = {...this.state.item};
        item[name] = value;
        this.setState({item});
    }

    async handleSubmit(event) {
        event.preventDefault();
        const {item} = this.state;

        await fetch('/http://localhost:3207/sjvodafoneservices/black/update', {
            method: (item.promoId) ? 'PUT' : 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item),
        });
        this.props.history.push('/admin/promo_catalog');
    }

    render() {
        const data = this.props.location.state;
        const title = <h2>{data.selectedId ? 'Edit Promo' : 'Add Promo'}</h2>;

        return (
            <>
                <PanelHeader size="sm"/>
                <div className="content">
                    <Row>
                        <Col md="8">
                            <Card>
                                <CardHeader>
                                    {title}
                                </CardHeader>
                                <CardBody>
                                    <Form onSubmit={this.handleSubmit}>
                                        <FormGroup>
                                            <Label for="promoId">Promo ID</Label>
                                            <Input name="promoId" id="promoId"
                                                   type="text"
                                                   placeholder="Promo ID"
                                                   value={data.selectedId || ''}
                                                   onChange={this.handleChange} />
                                        </FormGroup>
                                        <FormGroup>
                                            <Label for="item">Item</Label>
                                            <Input type="text" name="item" id="item"
                                                   placeholder="Item"
                                                   value={data.selectedIjCod || ''}
                                                   onChange={this.handleChange} />
                                        </FormGroup>
                                        <FormGroup>
                                            <Label for="title">Title</Label>
                                            <Input type="text" name="title" id="title"
                                                   placeholder="Title"
                                                   value={data.selectedTitle || ''}
                                                   onChange={this.handleChange} />
                                        </FormGroup>
                                            <FormGroup>
                                                <Label for="description">Description</Label>
                                                <Input type="text" name="description" id="description"
                                                       placeholder="Description"
                                                       value={data.selectedDescription}
                                                       onChange={this.handleChange} />
                                            </FormGroup>
                                        <FormGroup>
                                            <Button color="primary" type="submit">Save</Button>{' '}
                                            <Button color="secondary" tag={Link}
                                                    to="/admin/form_promo">Cancel</Button>
                                        </FormGroup>
                                    </Form>
                                </CardBody>
                            </Card>
                        </Col>
                    </Row>
                </div>
            </>
        );
    }

}

export default UpdatePromo;

I declared an empty item so I can check if the item is new or is to update. 我声明了一个空项目,所以我可以检查该项目是新的还是要更新的。 When I log the ID to the console it shows me empty beacuse of the emptyItem. 当我将ID登录到控制台时,由于emptyItem而显示为空。

How can I pass the ID that I already chose in the data table? 如何传递已经在数据表中选择的ID?

One way to do that would be to pass the selected id as a state in this.props.history.push() in your updatePromoClicked() function. 一种方法是在updatePromoClicked()函数的this.props.history.push()中将选定的ID作为状态传递。

this.props.history.push({
       pathname: '/admin/form_promo/'+id,
       state: {'selectedId': id}
});

Then in your Update page, you can access it as this.props.location.state.selectedId and set the state. 然后,在“更新”页面中,您可以使用this.props.location.state.selectedId进行访问并设置状态。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过选择表单将参数传递给URL? - How to pass parameters to a URL from a select form? 如何将表格中的选定行作为表单提交中的请求参数传递? - How to pass selected rows from a table as request parameters on form submit? 如何将参数从脚本传递到 html 表单值 - How to pass parameters from script to html form value React.js:如何从表单提交更新 API 调用 - React.js: How to update API call from form submit 如何通过表格传递交易数据参数(如金额) <hidden> 因为可以从客户端控制台更改 - How to pass transaction data parameters(like amount) through a form without <hidden> as this can be changed from the client console 如何从动态表单中获取值,将其传递给变量并使用JavaScript中的查询字符串参数重定向到URL? - How to get values from dynamic form, pass them to a variable and redirect to a URL with query string parameters in JavaScript? AngularJS 在表单中显示来自 api 的数据以更新它 - AngularJS show data from api in form to update it HTML API的HTML表单网址更新 - Html JavaScript Form Url update from API 如何将参数从servlet传递到JavaScript - How to pass parameters from servlet to JavaScript 如何将参数传递给ajax函数的回调 - How to pass parameters to callback from ajax function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM