ASP.NET Core API 和 React JS

Posted

技术标签:

【中文标题】ASP.NET Core API 和 React JS【英文标题】:ASP.NET Core API and React JS 【发布时间】:2020-06-26 16:51:12 【问题描述】:

我已经创建了 ASP.NET Core API 和 React CURD 实践示例。 I am following this example 但我使用了反应语义 ui 来查看。我是新来的反应和 ASP.NET 任何建议,以便我可以改进我的代码。

我能够获取、发布、放置和删除客户记录,但有一些小问题或要点我不知道如何实施。如下

1 - 我使用了 Modal,因此我可以将表单作为弹出窗口打开(AddCustomer 是用于添加和编辑记录的表单),因为我有两个功能可以打开和关闭 Modal,但我不知道如何从客户那里调用它们。 js 以及成功的 POST、PUT、DELETE 请求。

2 - 当我打开 FORM 以添加或编辑记录时,我无法将其存储在状态中。当我尝试输入输入字段时,它不会存储名称和地址。

3 - 您还可以在 Customer.js 中看到我正在隐藏表单并删除模式,但我想在 POST、PUT 和 DELETE 任务完成时关闭它们。

这是 Customer.js

import React from 'react';

import AddCustomer from './AddCustomer';
import CustomerView from './CustomerView';
import DeleteRecord from './DeleteRecord';

export default class Customer extends React.Component 

constructor(props) 
    super(props);
    this.state = 
        isAddCustomer:false,
        isEditCustomer:false,
        isDeleteCustomer:false,
        closeForm:false,
        singleCustomer:,
        deleteId:
    



onCreate = () => 
    console.log("is add customer true ")
    this.setState(isAddCustomer:true)


onFormControl = () =>
    this.setState(
        isAddCustomer:false,
        isEditCustomer:false
    )


onDeleteClick = customerId => 
    const headerTitle = "Customer";
    console.log("onDeleteClick")
    this.setState(
        isDeleteCustomer:true,
        deleteId:
            ID:customerId,
            title:headerTitle,
            open:true
        
    );


//New Customer record
onAddFormSubmit = data => 

    console.log("In add form submit")
    console.log(data)

    let customerApi = 'https://localhost:44387/api/Customers';
    let method = '';

    if(this.state.isEditCustomer)
        console.log("In Edit api")
        console.log(this.state.editCustomerId)
        customerApi = 'https://localhost:44387/api/Customers/' + this.state.editCustomerId;
        method = 'PUT'

    else
        console.log("In Add api")
        customerApi = 'https://localhost:44387/api/Customers';
        method = 'POST'

    

    const myHeader = new Headers(
        'Accept':'application/json',
            'Content-type':'application/json'
    );

    fetch(customerApi,
        method:method,
        headers:myHeader,
        body:JSON.stringify(data)

    )
    .then(res => res.json())
    .then(
        (result) => 
            this.setState(
                users:result,
                isAddCustomer:false,
                isEditCustomer:false
            )
        ,(error) => 
            this.setState( error );
        
    )


//Edit customer record
onEditCustomer = customerId => 

    //Get ID, name and address
    this.setState(
        editCustomerId:customerId
    );

    const customerApi = 'https://localhost:44387/api/Customers/'+customerId;

    const myHeader = new Headers(
        'Accept':'application/json',
            'Content-type':'application/json; charset=utf-8'
    );

    fetch(customerApi,
        method:'GET',
        headers:myHeader

    )
    .then(res => res.json())
    .then(
        (result) => 
            this.setState(
                isEditCustomer:true,
                isAddCustomer:false,
                singleCustomer:
                    customer:result,
                    isEditCustomer:true
                
            )
        ,(error) => 
            this.setState( error );
        
    )



//Delete Customer

onDeleteCustomer = customerId => 

    const customerApi = 'https://localhost:44387/api/Customers/'+customerId;

    const myHeader = new Headers(
        'Accept':'application/json',
            'Content-type':'application/json; charset=utf-8'
    );

    fetch(customerApi,
        method:'DELETE',
        headers:myHeader

    )
    .then(res => res.json())
    .then(
        (result) => 
            this.setState(
                isDeleteCustomer:false
            )
        ,(error) => 
            this.setState( error );
        
    )


render() 

    let form;
    if(this.state.isAddCustomer && !this.state.isEditCustomer)
        console.log("Add")
        form = <AddCustomer onAddFormSubmit=this.onAddFormSubmit
        isAddCustomer = this.state.isAddCustomer
        onFormControl = this.onFormControl/>
    else if(this.state.isEditCustomer && !this.state.isAddCustomer)
        console.log("Edit")
        form = <AddCustomer onAddFormSubmit=this.onAddFormSubmit
        singleCustomer = this.state.singleCustomer
        onFormControl = this.onFormControl/>
    else if(this.state.isDeleteCustomer)
        console.log("Delete")
        console.log(this.state.deleteId)
        form = <DeleteRecord onDeleteCustomer=this.onDeleteCustomer
        deleteId = this.state.deleteId
        />
    

    return (
        <div>
            form
            <br/>
            <CustomerView 
                onEditCustomer = this.onEditCustomer 
                onCreate = this.onCreate 
                onDeleteClick = this.onDeleteClick/>
        </div>
    )



这里是 CustomerView.js

import React from 'react';
import  Table, Button  from 'semantic-ui-react';

export default class CustomerView extends React.Component 

constructor(props) 
    super(props);
    this.state = 
        error: null,
        deleteTitle: "customer",
        isLoaded: false,
        formClose: false,
        singleCustomer: [],
        users: []
    


//fetch data 
componentDidMount() 

    const customerApi = 'https://localhost:44387/api/Customers';

    const myHeader = new Headers();
    myHeader.append('Content-type', 'application/json');
    myHeader.append('Accept', 'application/json');
    myHeader.append('Origin', 'https://localhost:44387');

    const options = 
        method: 'GET',
        myHeader
    ;

    fetch(customerApi, options)
        .then(res => res.json())
        .then(
            (result) => 
                this.setState(
                    users: result,
                    isLoaded: true
                );
            ,
            (error) => 
                this.setState(
                    isLoaded: false,
                    error
                );
            
        )


//Delete Customer

onDeleteCustomer = customerId => 

    const  users  = this.state;
    this.setState(
        users: users.filter(customer => customer.customerId !== customerId)
    );

    const customerApi = 'https://localhost:44387/api/Customers/' + customerId;

    const myHeader = new Headers(
        'Accept': 'application/json',
        'Content-type': 'application/json; charset=utf-8'
    );

    fetch(customerApi, 
        method: 'DELETE',
        headers: myHeader

    )
        .then(res => res.json())
        .then(
            (result) => 
                this.setState(

                )
            , (error) => 
                this.setState( error );
            
        )


render() 
    const  users  = this.state;

    return (
        <div>

            <Button color='blue' onClick=() => this.props.onCreate()>New Customer</Button>
            <br/>
            <br/>
            <Table celled textAlign='center'>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell>ID</Table.HeaderCell>
                        <Table.HeaderCell>Name</Table.HeaderCell>
                        <Table.HeaderCell>Address</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                        <Table.HeaderCell>Action</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body >
                    
                        users.map(user => (
                            <Table.Row key=user.customerId>

                                <Table.Cell>user.customerId</Table.Cell>
                                <Table.Cell>user.name</Table.Cell>
                                <Table.Cell>user.address</Table.Cell>

                                <Table.Cell>
                                    <Button color='blue' onClick=() => 
  this.props.onEditCustomer(user.customerId)>Edit</Button>
                                </Table.Cell>

                                <Table.Cell>
                                    <Button color='red' onClick=() => 
 this.props.onDeleteClick(user.customerId)>Delete</Button>
                                </Table.Cell>

                            </Table.Row>
                        ))
                    
                </Table.Body>

                <Table.Footer>
                    <Table.Row>
                        <Table.HeaderCell colSpan='5'>
                            No of Pages
                    </Table.HeaderCell>
                    </Table.Row>
                </Table.Footer>
            </Table>

        </div>
    )



这里是 AddCustomer.js

import React from 'react';
import  Button, Form, Modal  from 'semantic-ui-react';

export default class AddCustomer extends React.Component 

constructor(props) 
    super(props);
    this.state = 
        showCreateForm: false,
        addOrdit:false,
        id: "",
        name: "",
        address: "",
        formData: ,
        record: 
    
    if (props.isAddCustomer)
        this.state.showCreateForm = props.isAddCustomer;
    
    else if (props.singleCustomer) 
        console.log("Single customer")
        console.log(props.singleCustomer)
        this.state.id = props.singleCustomer.customer.customerId;
        this.state.name = props.singleCustomer.customer.name;
        this.state.address = props.singleCustomer.customer.address;
        this.state.record = props.singleCustomer.customer;
        this.state.showCreateForm = props.singleCustomer.isEditCustomer;
        this.state.addOrdit = props.singleCustomer.isEditCustomer;
        console.log(this.state.name)

    else if(props.closeForm)
        this.state.showCreateForm = props.closeForm;
    



handleChangeName = event => 
    const value = event.target.value;
    this.setState( name:value );


handleChangeAddress = event => 
    const value = event.target.value;
    this.setState( address:value );


handleSubmit = event => 
    event.preventDefault();
    if(this.state.addOrdit)

        this.setState(
            record: 
                customerId: this.state.id,
                name: this.state.name, 
                address: this.state.address
            
        );
    this.props.onAddFormSubmit(this.state.record);

    else
        this.setState(
            formData: 
                name: this.state.name, 
                address: this.state.address
            
        );
        this.props.onAddFormSubmit(this.state.formData);
    




//On cancel button click close Create user form
closeCreateForm = () => 
    this.setState( showCreateForm: false )
    this.props.onFormControl();


//Open Create new Customer form
openCreateCustomer = () => 
    this.setState( showCreateForm: true )


render() 

    let formTitle;
    if (this.state.id !== 0) 
        formTitle = "Edit Customer";
     else 
        formTitle = "New Customer";
    

    return (
        <div>
            <Modal size='small' 
            closeOnTriggerMouseLeave=false 
            open=this.state.showCreateForm>
                <Modal.Header>
                    formTitle
                </Modal.Header>
                <Modal.Content>
                    <Form onSubmit=this.handleSubmit>

                        <Form.Field>
                            <label>Name</label>
                            <input type="text" placeholder='Name' name="name"
                                value=this.state.name
                                onChange=this.handleChangeName />
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input type="text" placeholder='Address' name="address"
                                value=this.state.address
                                onChange=this.handleChangeAddress />
                        </Form.Field>

                        <br />
                        <Button type='submit' floated='right' color='green'>Create</Button>
                        <Button floated='right' onClick=this.closeCreateForm 
  color='black'>Cancel</Button>
                        <br />
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )



最后一个 DeleteRecord.js

import React from 'react';
import  Button, Modal, Icon  from 'semantic-ui-react';

export default class DeleteRecord extends React.Component 

constructor(props) 
    super(props);
    this.state = 
        ID:'',
        title: "",
        open: false
    
    if(props.deleteId)
        console.log(props.deleteId)
        this.state.ID = props.deleteId.ID;
        this.state.title = props.deleteId.title;
        this.state.open = props.deleteId.open;
    



//On cancel button click close Create user form
closeCreateForm = () => 
    console.log("Clicked")
    this.setState( open: false )


//Open Create new Customer form
openCreateCustomer = () => 
    this.setState( open: true )


render() 
    const title = "Delete " + this.state.title;

    return (
        <div>
            <Modal size='small' 
            closeOnTriggerMouseLeave=false 
            open=this.state.open>
                <Modal.Header>
                    title
                </Modal.Header>
                <Modal.Content>
                    <br />

                    Are you sure?

                    <br />
                    <br />
                    <Button floated='right' icon labelPosition='right' color='red'
                        value='true'
                        onClick=() => this.props.onDeleteCustomer(this.state.ID)
                    >
                        <Icon name='close' />
                        Delete
                    </Button>
                    <Button floated='right' color='black'
                        value='false'
                        onClick=this.closeCreateForm
                    >Cancel</Button>

                    <br />
                    <br />
                </Modal.Content>
            </Modal>
        </div>
    )



【问题讨论】:

【参考方案1】:

尝试使用 mobx 管理状态变量和使用 axios 调用 API,这将解决您的问题。

使用 mobx 的示例代码

import  observable, computed  from "mobx"

class OrderLine 
    @observable price = 0
    @observable amount = 1

    @computed get total() 
        return this.price * this.amount;
    

现在您可以在您的 Js 中导入 OrderLine 类,您可以使用和管理价格、金额的状态以动态呈现 UI

通过以下链接 https://mobx.js.org/README.html

【讨论】:

以上是关于ASP.NET Core API 和 React JS的主要内容,如果未能解决你的问题,请参考以下文章

从 ASP.NET CORE Web Api 获取 React 中的特定响应标头(例如,Content-Disposition)

同时对 Asp.Net core 2.0 MVC 应用程序 (cookie) 和 REST API (JWT) 进行身份验证

创建 Github CI/CD Pipeline 并部署到 Azure 云 Asp.net core 和 React Project

Firefox 上的 ASP.NET Core Web API CORS 错误,但在 Chrome 上没问题

在 ASP .NET Core 2.1 Web Api 中启用 CORS

在 ASP.NET Core API 中处理 id_token