如何在ReactJS中,在模态框保存按钮点击后刷新dataTable?

huangapple go评论79阅读模式
英文:

How to refresh dataTable in ReactJS after the modal save button is clicked?

问题

在我学习React的第二周。

我需要一些关于如何在我从模态框中点击保存按钮时刷新ReactJs中的dataTable的帮助。

这是我的结构。

我有一个ParameterMaintenance.jsx,它导入了DataTable组件。

import React from 'react';
import { ParameterDatable } from '../../components/ParameterDatatable';

export const ParameterMaintenance = () => {

  return (
    <div className='container mt-5'>
      <div></div>
      <ParameterDatatable/>
    </div>
  )
}

然后,我有一个ParameterDataTable.jsx文件,其中包含dataTable。请注意,在这里,我从DataTable的actions属性中调用了AddParameter.jsx,如下所示actions={<AddParameter/>},以添加一个按钮,显示处理新参数保存的模态框表单。

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import DataTableExtensions from 'react-data-table-component-extensions';
import 'react-data-table-component-extensions/dist/index.css';
import "bootstrap/dist/js/bootstrap.bundle.js";
import "bootstrap/dist/css/bootstrap.css";
import { Link } from "react-router-dom";
import { AddParameter } from './AddParameter';

export const ParameterDatatable= () => {

    const [parameters, setParameters] = useState([]);
    
    useEffect(() => {
        loadParameters();
    }, []);

    const loadParameters = async () => {
        const result = await axios.get("http://localhost:8080/parameters");
        setParameters(result.data);
    };
    
    const deleteParam = async (id) => {
        await axios.delete(`http://localhost:8080/parameter/${id}`);
        loadParameters();
    };

    const column = [
        // 列的定义
    ];

    return (
        <div className="datatable">
            <DataTableExtensions
                columns={column}
                data={parameters}
                print={false}
                export={false}
            >
                <DataTable 
                    title="Parameters"
                    columns={column} 
                    data={parameters} 
                    pagination
                    fixedHeader
                    fixedHeaderScrollHeight="450px"
                    highlightOnHover
                    actions={<AddParameter/>}
                    subHeader
                />
            </DataTableExtensions>
        </div>
    )
}

以下是我的AddParameter.jsx,这是保存新参数的模态框表单。

import React, { useState } from 'react';
import axios from "axios";
import "bootstrap/dist/js/bootstrap.bundle.js";
import "bootstrap/dist/css/bootstrap.css";
import { Link, useNavigate } from "react-router-dom";

export const AddParameter = () => {

    let navigate = useNavigate();

    const [parameter, setParameter] = useState({
        param_name: "",
        param_sequence_number: "",
        param_value: "",
    });

    const { param_name, param_sequence_number, param_value } = parameter;

    const onInputChange = (e) => {
        setParameter({ ...parameter, [e.target.name]: e.target.value });
    };   

    const onSubmit = async (e) => {
        e.preventDefault();
        console.log("Submitting");
        await axios.post("http://localhost:8080/parameter", parameter);
        navigate('admin/parameter1');
    };   

    return (
        <div>
            <button className="btn btn-sm btn-info"
                data-bs-toggle="modal"
                data-bs-target="#exampleModal">Create New</button>
            <div className="modal fade" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                {/* 模态框的定义 */}
            </div>
        </div>
    )
}

当我点击保存按钮时,我想关闭模态框并刷新DataTable,或者调用ParameterDataTable.jsx中从API获取数据的loadParameters函数。

尝试使用ReactJS中的navigate来尝试重新加载页面,但地址会像这样追加到当前地址。

英文:

On my second week of learning React.

I need some help on how to refresh the dataTable in reactJs when I clicked the save button from the modal.

Here is my structure.

I have a parameterMaintenance.jsx below which imports the DataTable Component

ParameterMaintenance.jsx

import React from &#39;react&#39;
import { ParameterDatable } from &#39;../../components/ParameterDatatable&#39;
export const ParameterMaintenance = () =&gt; {
return (
&lt;div className=&#39;container mt-5&#39;&gt;
&lt;div&gt;&lt;/div&gt;
&lt;ParameterDatatable/&gt;
&lt;/div&gt;
)
}

and then, I have a ParameterDataTable.jsx file that holds the dataTable.
notice that here, I called the AddParameter.jsx from the
DataTable actions property like this actions={&lt;AddParameter/&gt;}
to add a button that displays the modal form that handles the Saving of a new Parameter.

ParameterDatatable.jsx

import React, {useState, useEffect} from &#39;react&#39;
import axios from &#39;axios&#39;;
import DataTable from &#39;react-data-table-component&#39;; 
import DataTableExtensions from &#39;react-data-table-component-extensions&#39;;
import &#39;react-data-table-component-extensions/dist/index.css&#39;;
import &quot;bootstrap/dist/js/bootstrap.bundle.js&quot;;
import &quot;bootstrap/dist/css/bootstrap.css&quot;;
import { Link } from &quot;react-router-dom&quot;;
import { AddParameter } from &#39;./AddParameter&#39;;
export const ParameterDatatable= () =&gt; {
const [parameters, setParameters] = useState([]);
useEffect(() =&gt; {
loadParameters();
}, []);
const loadParameters = async () =&gt; {
const result = await axios.get(&quot;http://localhost:8080/parameters&quot;);
setParameters(result.data);
};
const deleteParam = async (id) =&gt; {
await axios.delete(`http://localhost:8080/parameter/${id}`);
loadParameters();
};
const column = [
{
name: &quot;Param Name&quot;,
selector: (row) =&gt; row.param_name,
width: &quot;180px&quot; ,
sortable: true,
alignItems: &#39;center&#39;,
display: &#39;flex&#39;,
},
{
name: &quot;Sequence Number&quot;,
selector: (row) =&gt; row.param_sequence_number,
width: &quot;150px&quot; ,
sortable: true,
},
{
name: &quot;Parameter Value&quot;,
selector: (row) =&gt; row.param_value,
width: &quot;150px&quot; ,
sortable: true,
},
{
name: &quot;&quot;,
width: &quot;110px&quot; ,
cell: row =&gt;  
&lt;div className=&quot;App&quot;&gt;
&lt;div className=&quot;openbtn text-center&quot;&gt;
&lt;button
type=&quot;button&quot;
class=&quot;btn btn-danger&quot;
data-bs-toggle=&quot;modal&quot;
data-bs-target=&quot;#myModal&quot;
&gt;
Delete
&lt;/button&gt;
&lt;div className=&quot;modal&quot; tabindex=&quot;-1&quot; id=&quot;myModal&quot;&gt;
&lt;div className=&quot;modal-dialog&quot;&gt;
&lt;div className=&quot;modal-content&quot;&gt;
&lt;div className=&quot;modal-header&quot;&gt;
&lt;h5 className=&quot;modal-title&quot;&gt;Danger&lt;/h5&gt;
&lt;button
type=&quot;button&quot;
className=&quot;btn-close&quot;
data-bs-dismiss=&quot;modal&quot;
aria-label=&quot;Close&quot;
&gt;&lt;/button&gt;
&lt;/div&gt;
&lt;div className=&quot;modal-body&quot;&gt;
&lt;p&gt;Do you want to remove this record premanently?&lt;/p&gt;
&lt;/div&gt;
&lt;div className=&quot;modal-footer&quot;&gt;
&lt;button
type=&quot;button&quot;
className=&quot;btn btn-secondary&quot;
data-bs-dismiss=&quot;modal&quot;
&gt;
Close
&lt;/button&gt;
&lt;button type=&quot;button&quot; className=&quot;btn btn-primary&quot; onClick={() =&gt; deleteParam(row.param_id)}
data-bs-dismiss=&quot;modal&quot;&gt;
Yes
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
,
},
{
name: &quot;&quot;,
width: &quot;110px&quot; ,
cell: row =&gt;  
&lt;button
className=&quot;btn btn-primary mx-2&quot;
onClick={() =&gt; deleteParam(row.param_id)}&gt;
Edit
&lt;/button&gt;,
},
]   
return (
&lt;div className=&quot;datatable&quot;&gt;
&lt;DataTableExtensions
columns={column}
data={parameters}
print={false}
export={false}
&gt;
&lt;DataTable 
title=&quot;Parameters&quot;
columns={column} 
data={parameters} 
pagination
fixedHeader
fixedHeaderScrollHeight=&quot;450px&quot;
highlightOnHover
actions={&lt;AddParameter/&gt;}
subHeader
/&gt;
&lt;/DataTableExtensions&gt;
&lt;/div&gt;
)
}

如何在ReactJS中,在模态框保存按钮点击后刷新dataTable?

And below is my AddParameter.jsx which is the modal form for saving new parameter

AddParameter.jsx

import React, {useState} from &#39;react&#39;
import axios from &quot;axios&quot;;
import &quot;bootstrap/dist/js/bootstrap.bundle.js&quot;;
import &quot;bootstrap/dist/css/bootstrap.css&quot;;
import { Link, useNavigate } from &quot;react-router-dom&quot;;
export const AddParameter = () =&gt; {
let navigate = useNavigate();
const [parameter, setParameter] = useState({
param_name: &quot;&quot;,
param_sequence_number: &quot;&quot;,
param_value: &quot;&quot;,
});
const {param_name, param_sequence_number, param_value} = parameter;
const onInputChange = (e) =&gt; {
setParameter({ ...parameter, [e.target.name]: e.target.value });
};   
const onSubmit = async (e) =&gt; {
e.preventDefault();
console.log(&quot;Submitting&quot;);
await axios.post(&quot;http://localhost:8080/parameter&quot;, parameter);
navigate(&#39;admin/parameter1&#39;);
};   
return (
&lt;div&gt;
&lt;button className=&quot;btn btn-sm btn-info&quot;
data-bs-toggle=&quot;modal&quot;
data-bs-target=&quot;#exampleModal&quot;&gt;Create New&lt;/button&gt;
&lt;div className=&quot;modal fade&quot; id=&quot;exampleModal&quot; tabindex=&quot;-1&quot; aria-labelledby=&quot;exampleModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
&lt;div className=&quot;modal-dialog&quot;&gt;
&lt;div className=&quot;modal-content&quot;&gt;
&lt;div className=&quot;modal-header&quot;&gt;
&lt;h5 className=&quot;modal-title&quot; id=&quot;exampleModalLabel&quot;&gt;New Parameter&lt;/h5&gt;
&lt;button type=&quot;button&quot; className=&quot;btn-close&quot; data-bs-dismiss=&quot;modal&quot; aria-label=&quot;Close&quot;&gt;&lt;/button&gt;
&lt;/div&gt;
&lt;div className=&quot;modal-body&quot;&gt;
&lt;form onSubmit={(e) =&gt; onSubmit(e)}&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label for=&quot;recipient-name&quot; className=&quot;col-form-label&quot;&gt;Parameter Name&lt;/label&gt;
&lt;input type={&quot;text&quot;} className=&quot;form-control&quot; placeholder=&quot;Param Name&quot; name=&quot;param_name&quot; value={param_name}
onChange={(e) =&gt; onInputChange(e)}/&gt;
&lt;/div&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label for=&quot;message-text&quot; className=&quot;col-form-label&quot;&gt;Sequence Number&lt;/label&gt;
&lt;input type={&quot;text&quot;} className=&quot;form-control&quot; placeholder=&quot;Sequence Number&quot; name=&quot;param_sequence_number&quot; value={param_sequence_number}
onChange={(e) =&gt; onInputChange(e)}/&gt;
&lt;/div&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label for=&quot;message-text&quot; className=&quot;col-form-label&quot;&gt;Parameter Value&lt;/label&gt;
&lt;input type={&quot;text&quot;} className=&quot;form-control&quot; placeholder=&quot;Value&quot; name=&quot;param_value&quot; value={param_value}
onChange={(e) =&gt; onInputChange(e)}/&gt;
&lt;/div&gt;
&lt;div className=&quot;modal-footer&quot;&gt;
&lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot; data-bs-dismiss=&quot;modal&quot;&gt;Close&lt;/button&gt;
&lt;button type=&quot;submit&quot; className=&quot;btn btn-primary&quot; data-bs-dismiss=&quot;modal&quot;&gt;Save Parameter&lt;/button&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
)
}

如何在ReactJS中,在模态框保存按钮点击后刷新dataTable?

what I wanted to do is when I clicked the Save button, it will close the modal and refresh the DataTable, or call the loadParameters function which gets data from API in ParameterDataTable.jsx

Tried to use the navigate in reactjs to try to reload the page but the address will just add to the current address like this.
如何在ReactJS中,在模态框保存按钮点击后刷新dataTable?

答案1

得分: 1

我理解你的问题,你想在删除用户值后刷新表格数据。你学到了在React中父子组件、子父组件的概念,并在项目中实现,从而解决了你的问题。

    // 例子:父组件

    function ParentA(){
       const [state,setstate] = useState(false);
    
       useEffect(() => {
          // 调用获取数据的方法;
       },[state]);
    
       return(
          <ChildA state={state} setstate={setstate} />
       )
    }
    
    // 子组件

    function ChildA({state, setstate}){
       const renderData = () => {
         setstate(!state);
       }

       return (
          <button onClick={renderData}>点击这里</button>
       )
    }
英文:

I understand your problem, you want to refresh table data after removing of user value. you learn about parent to child, child to parent concept in react and implement in project then solved your problem.

    //example: Parent Component;
function ParentA(){
const [state,setstate] = useState(false);
useEffect(() =&gt; {
//call fetch data method;
},[state]);
return(
&lt;ChildA state={state} setstate={setstate} /&gt;
)
}
//child component.
function ChildA({state, setstate}){
const renderData = () =&gt; {
setstate(!state);
}
return (
&lt;button onClick={renderData}&gt;Click here&lt;/button&gt;
)
}

答案2

得分: 1

这是一个可能的方法:

loadParameter函数作为AddParameter组件的prop传递,并在提交表单或点击按钮时调用它。

export const AddParameter = (props) => {

  ....

      const onSubmit = async (e) => {
        e.preventDefault();
        console.log("Submitting");
        await axios.post("http://localhost:8080/parameter", parameter);
        props.loadParameter()

      };  
  ...// or call it onClick

然后从父组件传递它

 <DataTable 
        title="Parameters"
        columns={column} 
        data={parameters} 
        pagination
        fixedHeader
        fixedHeaderScrollHeight="450px"
        highlightOnHover
        actions={<AddParameter loadParameter={loadParameter} />}
        
      subHeader

    />

最后,正如你在评论中所说想要清空文本框,你只需在关闭模态时调用一个函数。

const resetTextAfterClosing = () => {
    setParameter({
        param_name: "",
        param_sequence_number: "",
        param_value: "",
    });
}
英文:

This one possible approach:

Pass loadParameter function as a prop of AddParameter component and call it when sending the form or when clicking the button.

export const AddParameter = (props) =&gt; {
....
const onSubmit = async (e) =&gt; {
e.preventDefault();
console.log(&quot;Submitting&quot;);
await axios.post(&quot;http://localhost:8080/parameter&quot;, parameter);
props.loadParameter()
};  
...// or call it onClick

Then pass it from the parent component

 &lt;DataTable 
title=&quot;Parameters&quot;
columns={column} 
data={parameters} 
pagination
fixedHeader
fixedHeaderScrollHeight=&quot;450px&quot;
highlightOnHover
actions={&lt;AddParameter loadParameter = {loadParameter} /&gt;}
subHeader
/&gt;

Finally, as you said in the comments that you want to clear the text boxes, you just have to call a function when closing the modal.

const resetTextAfterClosing = () =&gt; {
setParameter({
param_name: &quot;&quot;,
param_sequence_number: &quot;&quot;,
param_value: &quot;&quot;,
});
}

答案3

得分: 0

在 "onSubmit" 函数中,设置 axios 响应,其中包含在 "setParameters" 中的所有数据,以及

useEffect(() => {
    loadParameters();
}, [parameters]);

希望这能解决你的问题。但是请了解一下 props drillingparent-child components

英文:

In "onSubmit" function, set the axios response which contains all data in "setParameters" and

useEffect(() =&gt; {
loadParameters();
}, [parameters]);

Hope, this will solve your problem. But have some studies about props drilling and parent-child components

huangapple
  • 本文由 发表于 2023年3月9日 13:48:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75680855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定