每次状态更改时,datatable组件都会重新呈现

时间:2020-06-30 20:35:22

标签: reactjs react-hooks

我已经使用react-data-table-component包创建了可重用的datatable组件。

    // these are the states I am using in the component
    // since parent component doesn't need to know about pages, total rows. I decided to 
    // define them inside the component and manage them from here. 

    const [data, setData] = useState([]);
    const [rows, setRows] = useState(10);
    const [totalRows, setTotalRows] = useState(0);
    const [page, setPage] = useState(1);


    useEffect(()=>{
       ApiService.createTransaction(data).then((response)=>{
        setData(response.data)
        setTotalRows(response.recordsFiltered);
        setPage(_page);
        props.setLoading(false);
      })
    },[])

我正在以这种方式使用此组件

 <CustomDatatable {parameters}/>

问题是,在我收到响应并尝试设置状态数据后,每次设置任何状态时,组件都会呈现。如何停止重新渲染。任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

您可以通过将变量useEffect添加到依赖项数组中来使useEffect依赖于变化的变量,该数组是 useEffect(()=>{ ApiService.createTransaction(data).then((response)=>{ setData(response.data) setTotalRows(response.recordsFiltered); setPage(_page); props.setLoading(false); }) },[data]) 的第二个参数。像这样:

useEffect

现在data仅在-- id 5: not in the image you've uploaded -- id 6: dstop value taken from the uploaded image create table wt( id, dstart, dstop ) as select 1 as id, 1.5 as DSTART, 3 as DSTOP from dual union all select 2 as id, 2 as DSTART, 3.5 as DSTOP from dual union all select 3 as id, 4.5 as DSTART, 8 as DSTOP from dual union all select 4 as id, 7 as DSTART, 9 as DSTOP from dual union all select 7 as id, 7 as DSTART, 12 as DSTOP from dual union all select 6 as id, 7 as DSTART, 11.5 as DSTOP from dual ; 更改时运行。您可以在该数组中添加其他内容以提供更多的依赖性。