UseState() 在按钮的 onClick 方法中没有更新。

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

UseState() is not updating on Button's onClick Method

问题

In the provided code, you are experiencing an issue where the rowsData in the button's onClick function doesn't reflect the updated data after fetching from the API and setting it using setRowsData. To address this issue, you can try using the useEffect hook to update the button's onClick function whenever the rowsData state changes. Here's how you can modify the code to achieve this:

import React, { useEffect, useState } from "react";
import GridTable from "@nadavshaar/react-grid-table";
import "./styles.css";

// ... (rest of the code)

const AsyncTable = () => {
  let [rowsData, setRowsData] = useState([]);

  // Add a useEffect to update the button's onClick function when rowsData changes
  useEffect(() => {
    const updatedColumns = [...columns];
    const buttonColumn = updatedColumns.find(
      (column) => column.id === "my-buttons-column"
    );

    if (buttonColumn) {
      buttonColumn.editorCellRenderer = ({
        tableManager,
        value,
        data,
        column,
        colIndex,
        rowIndex,
        onChange
      }) => (
        <div style={{ display: "inline-flex" }}>
          <button
            style={{ marginLeft: 20 }}
            onClick={(e) => tableManager.rowEditApi.setEditRowId(data.id)}
          >
            &#x270E;
          </button>
          <button
            style={{ marginLeft: 10, marginRight: 20 }}
            onClick={async (e) => {
              console.log({ rowsData });
              let rowsClone = [...rowsData];
              let updatedRowIndex = rowsClone.findIndex(
                (r) => r.id === data.id
              );
              rowsClone[updatedRowIndex] = data;
              setRowsData(rowsClone);
              tableManager.rowEditApi.setEditRowId(null);
            }}
          >
            &#x2714;
          </button>
        </div>
      );
    }
  }, [rowsData]);

  // ... (rest of the code)
};

With this modification, the useEffect will monitor changes in the rowsData state, and when it changes, it will update the onClick function of the button column to ensure that it uses the most up-to-date rowsData.

英文:

I'm very naive to ReactJS, in below code, in columns editorCellRenderer, there is a button onClick function, which uses rowsData of useState, so after fetching data from api, I update
rowsData using setRowsData, but in button rowsData always remains []. Because of this after edit of any column data, it is not reflected in UI.

section of code I'm referring:

 &lt;button
style={{ marginLeft: 10, marginRight: 20 }}
onClick={async (e) =&gt; {
console.log({ rowsData });
let rowsClone = [...rowsData];
let updatedRowIndex = rowsClone.findIndex(
(r) =&gt; r.id === data.id
);
rowsClone[updatedRowIndex] = data;
setRowsData(rowsClone);
tableManager.rowEditApi.setEditRowId(null);
}}
&gt;
&amp;#x2714;
&lt;/button&gt;

App.js

import React, { useEffect, useState } from &quot;react&quot;;
import GridTable from &quot;@nadavshaar/react-grid-table&quot;;
// import data from &quot;./data.json&quot;;
import &quot;./styles.css&quot;;
const convertData = (response, from = 0) =&gt; {
const rawData = response.data.nutritionData.data;
return rawData.map((raw, index) =&gt; {
const obj = {
id: from + index + 1,
_id: raw._id,
Index: from + index + 1,
ENERC_KCAL: raw.ENERC_KCAL.qty,
totalWeight: raw.totalWeight.qty,
FAT: raw.macro_nutrients.FAT.qty,
FASAT: raw.macro_nutrients.FASAT.qty,
FATRN: raw.macro_nutrients.FATRN.qty,
CHOCDF: raw.macro_nutrients.CHOCDF.qty,
FIBTG: raw.macro_nutrients.FIBTG.qty,
SUGAR: raw.macro_nutrients.SUGAR.qty,
PROCNT: raw.macro_nutrients.PROCNT.qty,
CHOLE: raw.micro_nutrients.CHOLE.qty,
NA: raw.micro_nutrients.NA.qty,
CA: raw.micro_nutrients.CA.qty,
MG: raw.micro_nutrients.MG.qty,
K: raw.micro_nutrients.K.qty,
FE: raw.micro_nutrients.FE.qty,
ZN: raw.micro_nutrients.ZN.qty,
P: raw.micro_nutrients.P.qty,
VITA_IU: raw.micro_nutrients.VITA_IU.qty,
VITC: raw.micro_nutrients.VITC.qty,
THIA: raw.micro_nutrients.THIA.qty,
RIBF: raw.micro_nutrients.RIBF.qty,
NIA: raw.micro_nutrients.NIA.qty,
VITB6A: raw.micro_nutrients.VITB6A.qty,
VITB12: raw.micro_nutrients.VITB12.qty,
VITD: raw.micro_nutrients.VITD.qty,
TOCPHA: raw.micro_nutrients.TOCPHA.qty,
VITK1: raw.micro_nutrients.VITK1.qty,
healthLabels: raw.healthLabels,
cautions: raw.cautions,
brand: raw.brand,
title: raw.title
};
return obj;
})
}
const AsyncTable = () =&gt; {
let [rowsData, setRowsData] = useState([]);
const columns = [
{
id: 0,
field: &quot;Index&quot;,
label: &quot;Index&quot;,
width: &quot;max-content&quot;
},
{
id: 31,
field: &quot;title&quot;,
label: &quot;title&quot;,
width: &quot;max-content&quot;
},
{
id: 1,
field: &quot;ENERC_KCAL&quot;,
label: &quot;ENERC_KCAL&quot;,
width: &quot;max-content&quot;
},
{
id: 2,
field: &quot;totalWeight&quot;,
label: &quot;totalWeight&quot;,
width: &quot;max-content&quot;
},
{
id: 3,
field: &quot;FAT&quot;,
label: &quot;FAT&quot;,
width: &quot;max-content&quot;
},
{
id: 4,
field: &quot;FASAT&quot;,
label: &quot;FASAT&quot;,
width: &quot;max-content&quot;
},
{
id: 5,
field: &quot;FATRN&quot;,
label: &quot;FATRN&quot;,
width: &quot;max-content&quot;
},
{
id: 6,
field: &quot;CHOCDF&quot;,
label: &quot;CHOCDF&quot;,
width: &quot;max-content&quot;
},
{
id: 7,
field: &quot;FIBTG&quot;,
label: &quot;FIBTG&quot;,
width: &quot;max-content&quot;
},
{
id: 8,
field: &quot;SUGAR&quot;,
label: &quot;SUGAR&quot;,
width: &quot;max-content&quot;
},
{
id: 9,
field: &quot;PROCNT&quot;,
label: &quot;PROCNT&quot;,
width: &quot;max-content&quot;
},
{
id: 10,
field: &quot;CHOLE&quot;,
label: &quot;CHOLE&quot;,
width: &quot;max-content&quot;
},
{
id: 11,
field: &quot;NA&quot;,
label: &quot;NA&quot;,
width: &quot;max-content&quot;
},
{
id: 12,
field: &quot;CA&quot;,
label: &quot;CA&quot;,
width: &quot;max-content&quot;
},
{
id: 13,
field: &quot;MG&quot;,
label: &quot;MG&quot;,
width: &quot;max-content&quot;
},
{
id: 14,
field: &quot;K&quot;,
label: &quot;K&quot;,
width: &quot;max-content&quot;
},
{
id: 15,
field: &quot;FE&quot;,
label: &quot;FE&quot;,
width: &quot;max-content&quot;
},
{
id: 16,
field: &quot;ZN&quot;,
label: &quot;ZN&quot;,
width: &quot;max-content&quot;
},
{
id: 17,
field: &quot;P&quot;,
label: &quot;P&quot;,
width: &quot;max-content&quot;
},
{
id: 18,
field: &quot;VITA_IU&quot;,
label: &quot;VITA_IU&quot;,
width: &quot;max-content&quot;
},
{
id: 19,
field: &quot;VITC&quot;,
label: &quot;VITC&quot;,
width: &quot;max-content&quot;
},
{
id: 20,
field: &quot;THIA&quot;,
label: &quot;THIA&quot;,
width: &quot;max-content&quot;
},
{
id: 21,
field: &quot;RIBF&quot;,
label: &quot;RIBF&quot;,
width: &quot;max-content&quot;
},
{
id: 22,
field: &quot;NIA&quot;,
label: &quot;NIA&quot;,
width: &quot;max-content&quot;
},
{
id: 23,
field: &quot;VITB6A&quot;,
label: &quot;VITB6A&quot;,
width: &quot;max-content&quot;
},
{
id: 24,
field: &quot;VITB12&quot;,
label: &quot;VITB12&quot;,
width: &quot;max-content&quot;
},
{
id: 25,
field: &quot;VITD&quot;,
label: &quot;VITD&quot;,
width: &quot;max-content&quot;
},
{
id: 26,
field: &quot;TOCPHA&quot;,
label: &quot;TOCPHA&quot;,
width: &quot;max-content&quot;
},
{
id: 27,
field: &quot;VITK1&quot;,
label: &quot;VITK1&quot;,
width: &quot;max-content&quot;
},
{
id: 28,
field: &quot;healthLabels&quot;,
label: &quot;healthLabels&quot;
},
{
id: 29,
field: &quot;cautions&quot;,
label: &quot;cautions&quot;
},
{
id: 30,
field: &quot;brand&quot;,
label: &quot;brand&quot;
},
{
id: &quot;my-buttons-column&quot;,
width: &quot;max-content&quot;,
pinned: true,
sortable: false,
resizable: false,
cellRenderer: ({
tableManager,
value,
data,
column,
colIndex,
rowIndex
}) =&gt; (
&lt;button
style={{ marginLeft: 20 }}
onClick={(e) =&gt; tableManager.rowEditApi.setEditRowId(data.id)}
&gt;
&amp;#x270E;
&lt;/button&gt;
),
editorCellRenderer: ({
tableManager,
value,
data,
column,
colIndex,
rowIndex,
onChange
}) =&gt; (
&lt;div style={{ display: &quot;inline-flex&quot; }}&gt;
&lt;button
style={{ marginLeft: 20 }}
onClick={(e) =&gt; tableManager.rowEditApi.setEditRowId(null)}
&gt;
&amp;#x2716;
&lt;/button&gt;
&lt;button
style={{ marginLeft: 10, marginRight: 20 }}
onClick={async (e) =&gt; {
console.log({ rowsData });
let rowsClone = [...rowsData];
let updatedRowIndex = rowsClone.findIndex(
(r) =&gt; r.id === data.id
);
rowsClone[updatedRowIndex] = data;
setRowsData(rowsClone);
tableManager.rowEditApi.setEditRowId(null);
}}
&gt;
&amp;#x2714;
&lt;/button&gt;
&lt;/div&gt;
)
}
]
const onRowsRequest = async (requestData, tableManager) =&gt; {
const limit = requestData.to - requestData.from;
const page = Math.floor(requestData.from / limit) + 1;
const response = await fetch(&#39;http://localhost:4000/api/v0/noauth/get/nutrition&#39;, {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;
},
body: JSON.stringify({
limit,
page
})
});
const jsonData = await response.json();
const rows = convertData(jsonData, requestData.from);
const totalRows = jsonData.data.nutritionData.totalDocuments;
setRowsData(rows);
return {
rows,
totalRows
};
};
return (
&lt;div className=&quot;App&quot;&gt;
&lt;GridTable
pageSizes={[10, 20, 30, 40, 50, 100]}
columns={columns} onRowsRequest={onRowsRequest} /&gt;
&lt;/div&gt;
);
};
export default AsyncTable;

App.css

.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

data.json to mimic actual api data:

{
&quot;status&quot;: &quot;success&quot;,
&quot;code&quot;: &quot;0000&quot;,
&quot;data&quot;: {
&quot;nutritionData&quot;: {
&quot;totalDocuments&quot;: 667888,
&quot;totalPages&quot;: 66789,
&quot;data&quot;: [
{
&quot;ENERC_KCAL&quot;: {
&quot;code&quot;: 208,
&quot;label&quot;: &quot;Energy&quot;,
&quot;qty&quot;: 2905.88,
&quot;unit&quot;: &quot;kcal&quot;
},
&quot;totalWeight&quot;: {
&quot;label&quot;: &quot;weight&quot;,
&quot;qty&quot;: 1906.75,
&quot;unit&quot;: &quot;g&quot;
},
&quot;_id&quot;: &quot;ea553309-53ee-41dd-8a87-b1a7aa138e72&quot;,
&quot;macro_nutrients&quot;: {
&quot;FAT&quot;: {
&quot;code&quot;: 204,
&quot;label&quot;: &quot;TOTAL_Fat&quot;,
&quot;qty&quot;: 181.32,
&quot;unit&quot;: &quot;g&quot;
},
&quot;FASAT&quot;: {
&quot;code&quot;: 606,
&quot;label&quot;: &quot;Saturated&quot;,
&quot;qty&quot;: 92.62,
&quot;unit&quot;: &quot;g&quot;
},
&quot;FATRN&quot;: {
&quot;code&quot;: 605,
&quot;label&quot;: &quot;Trans&quot;,
&quot;qty&quot;: 4.8,
&quot;unit&quot;: &quot;g&quot;
},
&quot;CHOCDF&quot;: {
&quot;code&quot;: 205,
&quot;label&quot;: &quot;Carbs&quot;,
&quot;qty&quot;: 220.47,
&quot;unit&quot;: &quot;g&quot;
},
&quot;FIBTG&quot;: {
&quot;code&quot;: 291,
&quot;label&quot;: &quot;Fiber&quot;,
&quot;qty&quot;: 16.96,
&quot;unit&quot;: &quot;g&quot;
},
&quot;SUGAR&quot;: {
&quot;code&quot;: 269,
&quot;label&quot;: &quot;Sugars&quot;,
&quot;qty&quot;: 43.6,
&quot;unit&quot;: &quot;g&quot;
},
&quot;PROCNT&quot;: {
&quot;code&quot;: 203,
&quot;label&quot;: &quot;Protein&quot;,
&quot;qty&quot;: 98.03,
&quot;unit&quot;: &quot;g&quot;
}
},
&quot;micro_nutrients&quot;: {
&quot;CHOLE&quot;: {
&quot;code&quot;: 601,
&quot;label&quot;: &quot;Cholesterol&quot;,
&quot;qty&quot;: 427.81,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;NA&quot;: {
&quot;code&quot;: 307,
&quot;label&quot;: &quot;Sodium&quot;,
&quot;qty&quot;: 2874.8,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;CA&quot;: {
&quot;code&quot;: 301,
&quot;label&quot;: &quot;Calcium&quot;,
&quot;qty&quot;: 2401.52,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;MG&quot;: {
&quot;code&quot;: 304,
&quot;label&quot;: &quot;Magnesium&quot;,
&quot;qty&quot;: 293.34,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;K&quot;: {
&quot;code&quot;: 306,
&quot;label&quot;: &quot;Potassium&quot;,
&quot;qty&quot;: 3371.02,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;FE&quot;: {
&quot;code&quot;: 303,
&quot;label&quot;: &quot;Iron&quot;,
&quot;qty&quot;: 4.28,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;ZN&quot;: {
&quot;code&quot;: 309,
&quot;label&quot;: &quot;Zinc&quot;,
&quot;qty&quot;: 13.51,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;P&quot;: {
&quot;code&quot;: 305,
&quot;label&quot;: &quot;Phosphorus&quot;,
&quot;qty&quot;: 2288.82,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;VITA_IU&quot;: {
&quot;code&quot;: 318,
&quot;label&quot;: &quot;Vitamin A&quot;,
&quot;qty&quot;: 3073.58,
&quot;unit&quot;: &quot;iu&quot;
},
&quot;VITC&quot;: {
&quot;code&quot;: 401,
&quot;label&quot;: &quot;Vitamin C&quot;,
&quot;qty&quot;: 24.98,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;THIA&quot;: {
&quot;code&quot;: 404,
&quot;label&quot;: &quot;Thiamin (B1)&quot;,
&quot;qty&quot;: 1.02,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;RIBF&quot;: {
&quot;code&quot;: 405,
&quot;label&quot;: &quot;Riboflavin (B2)&quot;,
&quot;qty&quot;: 2.35,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;NIA&quot;: {
&quot;code&quot;: 406,
&quot;label&quot;: &quot;Niacin (B3)&quot;,
&quot;qty&quot;: 13.12,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;VITB6A&quot;: {
&quot;code&quot;: 415,
&quot;label&quot;: &quot;Vitamin B6&quot;,
&quot;qty&quot;: 1.78,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;VITB12&quot;: {
&quot;code&quot;: 418,
&quot;label&quot;: &quot;Vitamin B12&quot;,
&quot;qty&quot;: 4.95,
&quot;unit&quot;: &quot;mcg&quot;
},
&quot;VITD&quot;: {
&quot;code&quot;: 324,
&quot;label&quot;: &quot;Vitamin D&quot;,
&quot;qty&quot;: 368.7,
&quot;unit&quot;: &quot;mcg&quot;
},
&quot;TOCPHA&quot;: {
&quot;code&quot;: 323,
&quot;label&quot;: &quot;Vitamin E&quot;,
&quot;qty&quot;: 9.81,
&quot;unit&quot;: &quot;mg&quot;
},
&quot;VITK1&quot;: {
&quot;code&quot;: 430,
&quot;label&quot;: &quot;Vitamin K&quot;,
&quot;qty&quot;: 42.5,
&quot;unit&quot;: &quot;mcg&quot;
}
},
&quot;healthLabels&quot;: [
&quot;FISH_FREE&quot;,
&quot;RED_MEAT_FREE&quot;,
&quot;PEANUT_FREE&quot;,
&quot;MUSTARD_FREE&quot;,
&quot;GLUTEN_FREE&quot;,
&quot;SESAME_FREE&quot;,
&quot;SOY_FREE&quot;,
&quot;TREE_NUT_FREE&quot;
],
&quot;cautions&quot;: [
&quot;DAIRY&quot;
],
&quot;supported_serving_units&quot;: [
{
&quot;label&quot;: &quot;serving&quot;,
&quot;unit_weight&quot;: &quot;263.0&quot;,
&quot;qty&quot;: &quot;1&quot;
},
{
&quot;label&quot;: &quot;grams&quot;,
&quot;unit_weight&quot;: 1,
&quot;qty&quot;: 1
}
],
&quot;ingredients&quot;: [
{
&quot;input&quot;: {
&quot;text&quot;: &quot;cups milk&quot;,
&quot;qty&quot;: [
&quot;2&quot;,
&quot;1/2&quot;
]
},
&quot;ingredient&quot;: &quot;milk&quot;,
&quot;unit&quot;: &quot;cup&quot;,
&quot;qty&quot;: 2.5,
&quot;matched_ingredient&quot;: &quot;milk&quot;,
&quot;weight&quot;: 610,
&quot;nutrition&quot;: {
&quot;protein&quot;: 19.215,
&quot;fat&quot;: 19.825,
&quot;carbs&quot;: 29.279999999999998,
&quot;sodium&quot;: 262.3
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;cups water&quot;,
&quot;qty&quot;: [
&quot;1&quot;,
&quot;1/2&quot;
]
},
&quot;ingredient&quot;: &quot;water&quot;,
&quot;unit&quot;: &quot;cup&quot;,
&quot;qty&quot;: 1.5,
&quot;matched_ingredient&quot;: &quot;water&quot;,
&quot;weight&quot;: 360,
&quot;nutrition&quot;: {
&quot;protein&quot;: 0,
&quot;fat&quot;: 0,
&quot;carbs&quot;: 0,
&quot;sodium&quot;: 14.4
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;cup butter&quot;,
&quot;qty&quot;: [
&quot;1/4&quot;
]
},
&quot;ingredient&quot;: &quot;butter&quot;,
&quot;unit&quot;: &quot;cup&quot;,
&quot;qty&quot;: 0.25,
&quot;matched_ingredient&quot;: &quot;butter&quot;,
&quot;weight&quot;: 56.75,
&quot;nutrition&quot;: {
&quot;protein&quot;: 0.482375,
&quot;fat&quot;: 46.029925,
&quot;carbs&quot;: 0.03405,
&quot;sodium&quot;: 364.9025
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;mashed potatoes 1 box&quot;,
&quot;qty&quot;: []
},
&quot;ingredient&quot;: &quot;potatoes&quot;,
&quot;unit&quot;: &quot;box&quot;,
&quot;qty&quot;: 1,
&quot;matched_ingredient&quot;: &quot;potato&quot;,
&quot;weight&quot;: 100,
&quot;nutrition&quot;: {
&quot;protein&quot;: 2.02,
&quot;fat&quot;: 0.09,
&quot;carbs&quot;: 17.47,
&quot;sodium&quot;: 6
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;can kernel corn&quot;,
&quot;qty&quot;: [
&quot;1&quot;
]
},
&quot;ingredient&quot;: &quot;kernel corn&quot;,
&quot;unit&quot;: &quot;can&quot;,
&quot;qty&quot;: 1,
&quot;matched_ingredient&quot;: &quot;corn kernel&quot;,
&quot;weight&quot;: 300,
&quot;nutrition&quot;: {
&quot;protein&quot;: 10.86,
&quot;fat&quot;: 4.26,
&quot;carbs&quot;: 77.61,
&quot;sodium&quot;: 12
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;cup cheddar cheese&quot;,
&quot;qty&quot;: [
&quot;1&quot;
]
},
&quot;ingredient&quot;: &quot;cheddar cheese&quot;,
&quot;unit&quot;: &quot;cup&quot;,
&quot;qty&quot;: 1,
&quot;matched_ingredient&quot;: &quot;cheddar cheese&quot;,
&quot;weight&quot;: 240,
&quot;nutrition&quot;: {
&quot;protein&quot;: 57.696,
&quot;fat&quot;: 81.16799999999999,
&quot;carbs&quot;: 3.192,
&quot;sodium&quot;: 1545.6
}
},
{
&quot;input&quot;: {
&quot;text&quot;: &quot;cup French fried onions&quot;,
&quot;qty&quot;: [
&quot;1&quot;
]
},
&quot;ingredient&quot;: &quot;french fried onions&quot;,
&quot;unit&quot;: &quot;cup&quot;,
&quot;qty&quot;: 1,
&quot;matched_ingredient&quot;: &quot;french fries&quot;,
&quot;weight&quot;: 240,
&quot;nutrition&quot;: {
&quot;protein&quot;: 7.752,
&quot;fat&quot;: 29.951999999999998,
&quot;carbs&quot;: 92.88000000000001,
&quot;sodium&quot;: 669.6
}
}
],
&quot;source&quot;: &quot;food.com&quot;,
&quot;brand&quot;: &quot;&quot;,
&quot;img_url&quot;: [],
&quot;title&quot;: &quot;crunchy onion potato bake&quot;,
&quot;actualTitle&quot;: &quot;Crunchy Onion Potato Bake&quot;,
&quot;url&quot;: &quot;http://www.food.com/recipe/crunchy-onion-potato-bake-479149&quot;,
&quot;updatedAt&quot;: &quot;2023-06-22T06:51:01.844Z&quot;
}]
&quot;displayMessage&quot;: &quot;Successful&quot;
}

I tried using useEffect and update button onClick function whenever state of rowsData changes. It didnt work.

I'm expecting to have rowsData in button onClick to be changed when I fetch api data and setRowsData in api call.

答案1

得分: 2

如果您想根据先前的值更新状态,最好使用函数式状态更新:

setRowsData((prev) =>
  prev.map((row) => {
    if (row.id === data.id) {
      return data;
    } else {
      return row;
    }
  })
)

这样,prev 将始终为您提供状态的当前值,您返回的内容将作为新值提供给它。在这里,我们从 prev 返回一个数组,通过遍历每个元素,如果满足条件,则返回 data,否则返回 row

英文:

If you want to update a state based on its previous value, better is to do it with the functional state update:

setRowsData((prev) =&gt;
  prev.map((row) =&gt; {
    if (row.id === data.id) {
      return data;
    } else {
      return row;
    }
  })
)

this way prev will always provide you with the current value of the state, and what you return is what you give as a new value to it. here we return an array from prev mapping through each element returning data if the condition is met, row otherwise.

答案2

得分: 1

尽管@AhmedSbai的回答完全有效,并且我发现比chatgpt提供的解决方案更好,但只是为了提供信息,我想展示chatGPT提供的解决方案,在尝试了30多种解决方案并浪费了2-3天之后,只有一种对我起作用。

在异步表中:

const rowsDataRef = useRef(rowsData);
useEffect(() => {
rowsDataRef.current = rowsData;
}, [rowsData]);

在editorCellRenderer中:

onClick={async (e) => {
let rowsClone = [...rowsDataRef.current];
let updatedRowIndex = rowsClone.findIndex(
(r) => r.id === data.id
);
rowsClone[updatedRowIndex] = data;
setRowsData(rowsClone);
tableManager.rowEditApi.setEditRowId(null);
}}
英文:

Though answer by @AhmedSbai totally worked fine and I found it better than solution provided by chatgpt, just for information I want to show solution given by chatGPT, after trying 30+ solutions and wasting 2-3 days, only one worked for me.

In Async Table:
` const rowsDataRef = useRef(rowsData);

useEffect(() =&gt; {
rowsDataRef.current = rowsData;
}, [rowsData]);`

In editorCellRenderer:

onClick={async (e) =&gt; {
let rowsClone = [...rowsDataRef.current];
let updatedRowIndex = rowsClone.findIndex(
(r) =&gt; r.id === data.id
);
rowsClone[updatedRowIndex] = data;
setRowsData(rowsClone);
tableManager.rowEditApi.setEditRowId(null);
}

huangapple
  • 本文由 发表于 2023年6月26日 18:53:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556010.html
匿名

发表评论

匿名网友

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

确定