简体   繁体   English

ReactJS 重复使用模态进行添加和编辑

[英]ReactJS Reuse Modal for Add and Edit

I have a ReactJS application, I have a page that has a table there is a create button for creating a new record that opens a modal to enter the data.我有一个 ReactJS 应用程序,我有一个包含表格的页面,其中有一个用于创建新记录的创建按钮,可以打开一个模式来输入数据。 That works fine but I want to reuse that same modal to edit the data as well.这很好用,但我也想重用相同的模式来编辑数据。 The user can select a row and then click edit, but I don't seem to be able to get the data I need.用户可以连续select然后点击编辑,但是我好像获取不到我需要的数据。

My Dialog is being included on the page as follows.我的对话框包含在页面中,如下所示。

render() {
        return (
            <div>
                <h2>Parameters</h2>
                <div className="row">
                    <ParameterDialog callback={this.fetchFromApi} messageCallback={this.props.messageCallback} open={this.state.modalOpen} openCallback={this.openModal} closeCallback={this.closeModal} selectedParameter={this.state.selectedRow} selectedParameterCallback={this.getSelectedParameter} />
                    <div className="col-sm-10">
                        <button type="button" onClick={this.onDelete} className="btn btn-danger pull-right" style={{marginRight: '15px', width: '80px'}}><span className="glyphicon glyphicon-remove"></span> Delete</button>
                        <button type="button" onClick={this.onEdit} className="btn btn-warning pull-right" style={{marginRight: '15px', width: '80px'}}><span className="glyphicon glyphicon-edit"></span> Edit</button>
                    </div>
                </div>
                <BootstrapTable data={this.state.parameters} options={options} pagination selectRow={{mode: 'radio', onSelect: this.onRowSelect}}>
                    <TableHeaderColumn isKey dataField='id'>ID</TableHeaderColumn>
                    <TableHeaderColumn dataField='groupId' filterFormatted dataFormat={enumFormatter} formatExtraData={this.props.parentState.parameterGroups}
                        filter={{type: 'SelectFilter', options: this.props.parentState.parameterGroups}}>Category</TableHeaderColumn>
                    <TableHeaderColumn dataField='subGroupId' filterFormatted dataFormat={enumFormatter} formatExtraData={this.state.subGroups}
                        filter={{type: 'SelectFilter', options: this.state.subGroups}}>Sub Category</TableHeaderColumn>
                    <TableHeaderColumn dataField='name' filter={ { type: 'TextFilter', delay: 500 } }>Parameter</TableHeaderColumn>
                    <TableHeaderColumn dataField='type' filterFormatted dataFormat={enumFormatter} formatExtraData={this.props.parentState.parameterTypes}
                                       filter={{type: 'SelectFilter', options: this.props.parentState.parameterTypes}}>Type</TableHeaderColumn>
                    <TableHeaderColumn dataField='reboot'>Reboot</TableHeaderColumn>
                </BootstrapTable>
            </div>
        )
    }

In the Dialog component I am calling trying to fetch the data in componentDidMount problem being it will always be null when the component mounts because user hasn't chosen anything yet.在 Dialog 组件中,我正在调用尝试获取 componentDidMount 问题中的数据,因为当组件安装时它总是 null 因为用户还没有选择任何东西。

componentDidMount() {

    console.debug("ParameterDialog mounted...");

    axios({
        method: 'get',
        url: urlBuilder.buildUrl('/api/groups'),
        data: {},
    }).then(resp => {
        this.setState({groups: resp.data});
    }).catch(error => {
        this.props.messageCallback("Ohhhh snap!", "Unable to fetch data from server", Constants.MESSAGE_ERROR)
    });

    axios({
        method: 'get',
        url: urlBuilder.buildUrl(`/api/groups/2/subgroups`),
        data: {}
    }).then(resp => {
        this.setState({subGroups: resp.data});
    }).catch(error => {
        this.props.messageCallback("Ohhhh snap!", "Unable to fetch data from server", Constants.MESSAGE_ERROR)
    });

    // init the state
    this.setState({typeOptions: ['BOOLEAN', 'STRING', 'INTEGER', 'DECIMAL']});
    this.setState({selectedGroup: 2, parameter: '', description: null, type: 'BOOLEAN', rebootRequired: false});

    // if parameterId is present load record from database (Edit mode)
    let parameterId = this.props.selectedParameterCallback();
    if (parameterId) {
        console.debug("Parameter is being edited, loading record");
        this.editMode = true;
        this.loadRecord();
    }
}

The modal open property is being bound to parent, but what I really need to happen is when open changes it checked the selectedParameter value and then makes the decision to call the API or not.模态打开属性被绑定到父级,但我真正需要发生的是当打开更改时它检查 selectedParameter 值,然后决定是否调用 API。

return (
        <div className="col-sm-2">
            <Button bsStyle="primary" onClick={this.props.openCallback}>Add Parameter</Button>
            <Modal show={this.props.open} onHide={this.closeCallback}>
                <Modal.Header>
                    <Modal.Title>Add / Edit Parameter</Modal.Title>
                </Modal.Header>
                .........

However this seems to be in contrast to how ReactJS wants to work, the only thing I can think of is to move all the state into the parent component but that will make it huge and really doesn't seem like good module design.然而,这似乎与 ReactJS 想要的工作方式形成对比,我唯一能想到的是将所有 state 移动到父组件中,但这会使它变得庞大并且看起来真的不像好的模块设计。

Is there another way to accomplish this?还有另一种方法可以做到这一点吗? If I could call a child function from parent that would accomplish what I need to do I think.如果我可以从父母那里打电话给孩子 function,我认为这将完成我需要做的事情。

React is best for just managing the view, but not the actions behind the views. React最适合管理视图,而不是视图背后的操作。

I highly recommend using Redux to help with this. 我强烈建议使用Redux来帮助解决这个问题。 With Redux, you would have your AJAX calls in an action creator and your application state would be maintained in the reducer. 使用Redux,您可以在动作创建器中进行AJAX调用,并且您的应用程序状态将保留在reducer中。 That would simplify your React considerably and make it easier to maintain. 这将大大简化您的React并使其更易于维护。

In regards to your question about where to maintain state, you would keep that in the Redux state using a reducer, and all of the state changes would propagate to your React components as props. 关于您在哪里维护状态的问题,您可以使用reducer将其保留在Redux状态,并且所有状态更改都将作为props传播到您的React组件。 You want to have a top-down hierarchical design so that the parent component (parent to the dialog) would pass the dialog content as a prop to the dialog. 您希望采用自上而下的层次结构设计,以便父组件(对话框的父级)将对话框内容作为对象传递给对话框。 The dialog would send events to the action creator to do the loading and updating. 该对话框将向活动创建者发送事件以进行加载和更新。

I do have the same problem but I think a have the logic in place, one way to do it is to create an initialstate of the form or object as empty strings, when an object is sent to the modal it will initialize the object with an id, if its new object render Addnew if an id is present then render Update item, you can implement other logics but this one seems to be simplest one我确实有同样的问题,但我认为逻辑已经到位,一种方法是创建表单的初始状态或 object 作为空字符串,当 object 发送到模态时,它将初始化 object id,如果它的新 object 呈现 Addnew 如果存在 id 则呈现 Update 项,您可以实现其他逻辑,但这个似乎是最简单的

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM