如何在反应中更新表列的数据? [英] How to update data for table column in react?

查看:33
本文介绍了如何在反应中更新表列的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在引导程序中的表有问题.我正在从服务器获取有关时间表的数据.这些数据我保存在状态.接下来我正在创建表.(创建手机和电脑的两种方式,只是改变天和小时的位置).每列都包含组件 SubjectColumn(一列中会有更多数据,如类和主题名称).因此,当我单击此主题列时,我需要使用单击的主题数据打开模态,并且在选择模态中的主题列表后,我必须将主题更改为新的主题.我在我的模态中获得了主题数据,但我不知道如何将它们更改为新的.有什么想法吗?

<预><代码>导出类计划扩展组件{静态上下文类型 = LoggedInuserContext;构造函数(道具){超级(道具);this.state = {编辑模式:假,openModal:假,时间表:空,modalShow:假,我的主题:空,选定主题:空};this.resize = () =>this.forceUpdate();}changeModalState() {this.setState({modalShow: !this.state.modalShow})}选择主题(主题){this.setState({selectedSubject:subject},this.changeModalState);}componentDidMount() {window.addEventListener('resize', this.resize)this.getTimeTable().then(r =>this.setState({isScheduleLoaded: true}));this.getMySubjects();}componentWillUnmount() {window.removeEventListener('resize', this.resize)}异步 getTimeTable() {如果(this.context == null)返回;const response = await fetch('UserController/GetTimeTable/' + this.context.user.id + '/' + this.context.company + '/' + this.context.role.id);this.setState({schedule: await response.json()});}异步 getMySubjects() {如果(this.context == null)返回;const response = await fetch('SubjectTreeController/GetUserSubjectsList/' + this.context.user.id + '/' + this.context.company + '/' + this.context.role.id);this.setState({mySubjects: await response.json()});}创建内容(){if (!this.state.isScheduleLoaded === true) 返回;让 header_data = [];让 body_data = [];//对于移动其他电脑如果(window.innerWidth <768){//表头this.state.schedule.days.forEach(day => {header_data.push(day.name.substring(0, 2))});//表体for (let i = 0; i {row.other.push(day.slots[i]);});body_data.push(row);}} 别的 {//表头this.state.schedule.days[0].slots.forEach(slot => {header_data.push(slot.order)});//表体this.state.schedule.days.forEach(day => {让行 = {第一列:[],其他: []};row.firstColumn.push(day.name);day.slots.map(slot => row.other.push(slot));body_data.push(row);});}让头 = this.createTableHead(header_data);让 body = this.createRows(body_data);返回 (<><头>{头}</thead>{身体}</tbody></>);}创建表头(数据){返回 (<tr><td></td>{data.map((d, k) => {return (<th key={k} className={"text-center"}> {d} </th>)})}</tr>);}创建行(数据){常量项 = [];for (let i = 0; i < data.length; i++) {常量行 = [];for (让 j = 0; j < data[i].other.length; j++) {if (data[i].other[j].subject !== null) {row.push(<td key={j} className={"text-center "}><SubjectColumn editMode={this.state.editMode}主题={数据[i].其他[j].主题}selectSubject={this.selectSubject.bind(this)}></SubjectColumn></td>);} 别的 {row.push(<td key={j} className={"text-center "}><SubjectColumn editMode={this.state.editMode}主题={空}selectSubject={this.selectSubject.bind(this)}></SubjectColumn></td>);}}项目.推(<tr key={i}><td>{data[i].firstColumn}</td>{排}</tr>);}退换货品;}加载(){if (this.state.schedule === null)返回 (<div className={"d-flex flex-column justify-content-center text-center"}><div><Spinner animation="grow" variant="success"/><Spinner animation="grow" variant="danger"/><Spinner animation="grow" variant="warning"/>

<span>Načítam rozvrh</span>

);}showActionButtons() {常量项 = [];如果(this.state.editMode){items.push(<Button key={"save"} className={"px-4 mx-1"} variant={"success"}onClick={this.startEditing.bind(this)}>Uložiť)}项目.推(<下拉键={"settings"} alignRight><Dropdown.Toggle variant="dark" id="dropdown-basic"><FontAwesomeIcon icon={faCog} size={"lg"}/></Dropdown.Toggle><下拉菜单><Dropdown.Item onClick={this.startEditing.bind(this)}>Edituj rozvrh</Dropdown.Item></Dropdown.Menu></下拉菜单>);退换货品;}开始编辑(){this.setState({editMode: !this.state.editMode});}openScheduleSetting() {console.log("打开");//this.setState({openModal: true});}closeScheduleSetting() {console.log("关闭");//this.setState({openModal: false});}使成为() {返回 (<div className={"w-100"} id="schedule"><div className={"d-flex justify-content-center my-2"}><h3 className={"my-1 text-left flex-grow-1 pl-2"}>Rozvrh hodín</h3>{this.showActionButtons()}

<表格条纹边框悬停>{this.createContent()}</表>{this.loading()}<ScheduleSelectModal subject={this.state.selectedSubject} subjectlist={this.state.mySubjects} show={this.state.modalShow} onHide={this.changeModalState.bind(this)}></ScheduleSelectModal>

);}}

主题列

export class SubjectColumn extends Component {showModalInParrent(){console.log(this.props);this.props.selectSubject(this.props.subject);}创建单元(){让项目 = 空;如果(this.props.editMode){if(this.props.subject === null){return ( <Button className={"w-100 h-100"} onClick={this.showModalInParrent.bind(this)}> </Button>)}项目 = (<片段><Button className={"w-100 h-100"} onClick={this.showModalInParrent.bind(this)}>{this.props.subject.acronym } </Button></片段>);退换货品;} 别的 {if(this.props.subject === null){返回;}返回 (this.props.subject.acronym );}}使成为() {返回 (<div className="w-100 h-100">{this.createCell()}

);}}

模态:

import React, {Component, Fragment} from "react";从react-bootstrap/Modal"导入模态;从react-bootstrap/ButtonGroup"导入 ButtonGroup;从react-bootstrap/Button"导入按钮;导出类 ScheduleSelectModal 扩展组件 {componentDidUpdate(prevProps,prevState,快照){console.log("模态道具:");console.log(this.props.subject);}创建列表(){让项目 = [];if (this.props.subjectslist !== null)this.props.subjectslist.map(subject =>items.push(<Button key={subject.id} block className={"my-1"}>{subject.name} </Button>));退换货品;}渲染头(){if(this.props.subject === null){返回(<p>Vyberťe subjekt ktorý chcete nahradiť</p>)}别的{返回( <p>{this.props.subject.name }</p>);}}使成为() {返回 (<模态{...this.props}大小=lg"aria-labelledby="contained-modal-title-vcenter"居中><Modal.Header closeButton><Modal.Title id="contained-modal-title-vcenter">{this.renderHeader()}</Modal.Title></Modal.Header><模态体><ButtonGroup vertical className={"w-100"}>{this.createList()}</ButtonGroup></Modal.Body></模态>);}}

这很像我的棚屋

对象编号:1日期更新:2020-03-24T17:36:48.66"天:阵列(5)0: {slots: Array(8), id: 1, order: 1, name: "Pondelok", acronym: "PO", ...}1:插槽:阵列(8)0:{订单:0,主题:空,学生组:空}1:{顺序:1,主题:空,学生组:空}2: {order: 2, subject: {…}, studentGroup: null}3:订单:3主题:笔记: ""编号:5名称:《生物学》缩写:B"__proto__:对象学生组:空__proto__:对象4: {order: 4, subject: {…}, studentGroup: null}5:{订单:5,主题:空,学生组:空}6:{订单:6,主题:空,学生组:空}7:{订单:7,主题:空,学生组:空}长度:8__proto__:数组(0)编号:2订单:2名称:尤托洛克"缩写:UT"是周末:0__proto__:对象2: {slots: Array(8), id: 3, order: 3, name: "Streda", acronym: "ST", ...}3: {slots: Array(8), id: 4, order: 4, name: "Štvrtok", acronym: "ŠT", ...}4: {slots: Array(8), id: 5, order: 5, name: "Piatok", acronym: "PIA", ...}长度:5__proto__:数组(0)__proto__:对象

解决方案

如果我理解你的问题,这可能对你有用:

  1. 在您显示 selectedSubject 的模式中,用输入元素替换您想要编辑的每个值(文本).
  2. 改变输入中的值应该更新 Schedule 组件中的 state.selectedSubject 或者你可能在模态中有状态来捕获编辑过的 selectedSubject,但是为什么如果不需要,可以复制数据.我会更新父组件状态.
  3. Schedule 组件应该具有使用编辑过的数据发出放置(或补丁)请求的方法.
  4. 将此方法传递给模态.
  5. 向模态添加保存"按钮.完成编辑后,点击保存"按钮应该会触发传递的方法.
  6. 可选:您可以在模态中显示成功消息(成功或错误)

Hi i have problem with my table in bootstrap. I am getting data from server about timetable. This data i am saving in state. Next i am creating table. (Two ways of creating mobile and pc, just changing position of days and hours). Every column contains component SubjectColumn (there will be more data in one column like class and subject name). So when I click on this subject column i need to open modal with clicked subject data and after choosing of list of subjects in modal, I have to change subject for new one. I get subject data in my modal but i don't know how to change them for new one. Any idea please?


export class Schedule extends Component {
    static contextType = LoggedInuserContext;

    constructor(props) {
        super(props);
        this.state = {
            editMode: false,
            openModal: false,
            schedule: null,
            modalShow: false,
            mySubjects: null,
            selectedSubject:null
        };

        this.resize = () => this.forceUpdate();
    }

    changeModalState() {
        this.setState({modalShow: !this.state.modalShow})
    }


    selectSubject(subject){
        this.setState({selectedSubject:subject},this.changeModalState);
    }


    componentDidMount() {
        window.addEventListener('resize', this.resize)
        this.getTimeTable().then(r =>
            this.setState({isScheduleLoaded: true})
        );
        this.getMySubjects();
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.resize)
    }

    async getTimeTable() {
        if (this.context == null) return;
        const response = await fetch('UserController/GetTimeTable/' + this.context.user.id + '/' + this.context.company + '/' + this.context.role.id);
        this.setState({schedule: await response.json()});
    }

    async getMySubjects() {
        if (this.context == null) return;
        const response = await fetch('SubjectTreeController/GetUserSubjectsList/' + this.context.user.id + '/' + this.context.company + '/' + this.context.role.id);
        this.setState({mySubjects: await response.json()});
    }

    createContent() {
        if (!this.state.isScheduleLoaded === true) return;

        let header_data = [];
        let body_data = [];

        //For mobile else pc
        if (window.innerWidth < 768) {
            //Header of table
            this.state.schedule.days.forEach(day => {
                header_data.push(day.name.substring(0, 2))
            });

            //Body of table
            for (let i = 0; i < this.state.schedule.days[0].slots.length; i++) {
                let row = {
                    firstColumn: i,
                    other: []
                };
                this.state.schedule.days.forEach((day, key) => {
                    row.other.push(day.slots[i]);
                });

                body_data.push(row);
            }
        } else {
            //Header of table
            this.state.schedule.days[0].slots.forEach(slot => {
                header_data.push(slot.order)
            });

            //Body of table
            this.state.schedule.days.forEach(day => {
                let row = {
                    firstColumn: [],
                    other: []
                };
                row.firstColumn.push(day.name);
                day.slots.map(slot => row.other.push(slot));
                body_data.push(row);
            });
        }

        let head = this.createTableHead(header_data);
        let body = this.createRows(body_data);

        return (
            <>
                <thead>
                {head}
                </thead>
                <tbody>
                {body}
                </tbody>
            </>
        );
    }

    createTableHead(data) {
        return (
            <tr>
                <td></td>
                {data.map((d, k) => {
                    return (<th key={k} className={"text-center"}> {d} </th>)
                })}
            </tr>
        );
    }

    createRows(data) {
        const items = [];
        for (let i = 0; i < data.length; i++) {
            const row = [];

            for (let j = 0; j < data[i].other.length; j++) {
                if (data[i].other[j].subject !== null) {
                    row.push(<td key={j} className={"text-center "}><SubjectColumn editMode={this.state.editMode}
                                                                                   subject={data[i].other[j].subject}
                                                                                    selectSubject={this.selectSubject.bind(this)}>
                    </SubjectColumn>
                    </td>);
                } else {
                    row.push(<td key={j} className={"text-center "}><SubjectColumn editMode={this.state.editMode}
                                                                                   subject={null}
                                                                                   selectSubject={this.selectSubject.bind(this)}
                                                                                   >
                                                                                   </SubjectColumn>
                    </td>);
                }
            }

            items.push(
                <tr key={i}>
                    <td>{data[i].firstColumn}</td>
                    {row}
                </tr>
            );
        }
        return items;

    }

    loading() {
        if (this.state.schedule === null)
            return (
                <div className={"d-flex flex-column justify-content-center text-center"}>
                    <div>
                        <Spinner animation="grow" variant="success"/>
                        <Spinner animation="grow" variant="danger"/>
                        <Spinner animation="grow" variant="warning"/>
                    </div>
                    <span>Načítam rozvrh</span>
                </div>
            );
    }

    showActionButtons() {
        const items = [];

        if (this.state.editMode) {
            items.push(<Button key={"save"} className={"px-4 mx-1"} variant={"success"}
                               onClick={this.startEditing.bind(this)}>Uložiť</Button>)
        }
        items.push(
            <Dropdown key={"settings"} alignRight>
                <Dropdown.Toggle variant="dark" id="dropdown-basic">
                    <FontAwesomeIcon icon={faCog} size={"lg"}/>
                </Dropdown.Toggle>

                <Dropdown.Menu>
                    <Dropdown.Item onClick={this.startEditing.bind(this)}>Edituj rozvrh</Dropdown.Item>
                </Dropdown.Menu>
            </Dropdown>
        );
        return items;
    }

    startEditing() {
        this.setState({editMode: !this.state.editMode});
    }


    openScheduleSetting() {
        console.log("open");
//        this.setState({openModal: true});
    }

    closeScheduleSetting() {
        console.log("close");

        //      this.setState({openModal: false});
    }

    render() {
        return (
            <div className={"w-100"} id="schedule">
                <div className={"d-flex justify-content-center my-2"}>
                    <h3 className={"my-1 text-left flex-grow-1  pl-2"}>Rozvrh hodín</h3>
                    {this.showActionButtons()}
                </div>
                <Table striped bordered hover>
                    {this.createContent()}
                </Table>
                {this.loading()}
                <ScheduleSelectModal subject={this.state.selectedSubject} subjectslist={this.state.mySubjects} show={this.state.modalShow} onHide={this.changeModalState.bind(this)}>
                </ScheduleSelectModal>
            </div>
        );
    }
}

SubjectColumn

export class SubjectColumn extends Component {

    showModalInParrent(){
        console.log(this.props);
        this.props.selectSubject(this.props.subject);
    }

    createCell() {
        let items = null;
        if (this.props.editMode) {
            if(this.props.subject === null){
                return (  <Button className={"w-100 h-100"} onClick={this.showModalInParrent.bind(this)}>  </Button>)
            }

            items = (
                <Fragment>
                    <Button className={"w-100 h-100"} onClick={this.showModalInParrent.bind(this)}> {this.props.subject.acronym } </Button>
                </Fragment>
            );
            return items;
        } else {
            if(this.props.subject === null){
            return;
            }

            return (this.props.subject.acronym  );
        }
    }

    render() {
        return (
            <div className="w-100 h-100">
                {this.createCell()}
            </div>
        );
    }
}

Modal:

import React, {Component, Fragment} from "react";
import Modal from "react-bootstrap/Modal";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import Button from "react-bootstrap/Button";

export class ScheduleSelectModal extends Component {

   componentDidUpdate(prevProps, prevState, snapshot) {
       console.log("modal props:");
       console.log(this.props.subject);
   }

    createList() {
        let items = [];
        if (this.props.subjectslist !== null)
            this.props.subjectslist.map(subject =>
                items.push(<Button key={subject.id} block className={"my-1"}>{subject.name} </Button>)
            );

        return items;
    }

    renderHeader(){
       if(this.props.subject === null){
           return(
               <p>
                   Vyberťe subjekt ktorý chcete nahradiť
               </p>
           )
       }
       else{
          return(   <p>
              {this.props.subject.name }
          </p>);
        }
    }

    render() {
        return (
            <Modal
                {...this.props}
                size="lg"
                aria-labelledby="contained-modal-title-vcenter"
                centered
            >
                <Modal.Header closeButton>
                    <Modal.Title id="contained-modal-title-vcenter">
                        {this.renderHeader()}
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <ButtonGroup vertical className={"w-100"}>
                        {this.createList()}
                    </ButtonGroup>
                </Modal.Body>
            </Modal>
        );
    }
}

This loos like my shedule object

Object
id: 1
dateUpdated: "2020-03-24T17:36:48.66"
days: Array(5)
0: {slots: Array(8), id: 1, order: 1, name: "Pondelok", acronym: "PO", …}
1:
slots: Array(8)
0: {order: 0, subject: null, studentGroup: null}
1: {order: 1, subject: null, studentGroup: null}
2: {order: 2, subject: {…}, studentGroup: null}
3:
order: 3
subject:
note: ""
id: 5
name: "Biológia"
acronym: "B"
__proto__: Object
studentGroup: null
__proto__: Object
4: {order: 4, subject: {…}, studentGroup: null}
5: {order: 5, subject: null, studentGroup: null}
6: {order: 6, subject: null, studentGroup: null}
7: {order: 7, subject: null, studentGroup: null}
length: 8
__proto__: Array(0)
id: 2
order: 2
name: "Utorok"
acronym: "UT"
isWeekend: 0
__proto__: Object
2: {slots: Array(8), id: 3, order: 3, name: "Streda", acronym: "ST", …}
3: {slots: Array(8), id: 4, order: 4, name: "Štvrtok", acronym: "ŠT", …}
4: {slots: Array(8), id: 5, order: 5, name: "Piatok", acronym: "PIA", …}
length: 5
__proto__: Array(0)
__proto__: Object

解决方案

If I've undeerstood your q, this might work for you:

  1. In the modal where you show selectedSubject, replace each value (text) you want to edit with input element.
  2. changing value in input should update state.selectedSubject in Schedule component or you might have state in modal to capture edited selectedSubject, but why duplicating data if you don't have to. I would go with updating parent component state.
  3. Schedule component should have method which will make put (or patch) request with edited data.
  4. Pass this method to the modal.
  5. Add "Save" button to the modal. When you finish editing, clicking on "Save" button should fire passed method.
  6. Optional: you can have success message in your modal (success or error)

这篇关于如何在反应中更新表列的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆