React(搭配Ant Design表格)非常慢:如何优化?

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

React (with Ant Design table) is **really** slow: how to optimize?

问题

我创建了一个使用 Ant Design 表格组件的 React 小型调度系统。我的问题是,当我们添加大约60行(听起来不是很多,对吧?)时,系统变得非常慢(即使水平滚动也会产生一些小的延迟)。像我做的任何操作可能需要大约5秒钟:

React(搭配Ant Design表格)非常慢:如何优化?

你有任何关于我做错了什么,以及如何调试这些问题的想法吗?

编辑 我还尝试了添加 memouseCallback,但问题仍然存在...

示例代码:

<!doctype html>
<html lang="en">
  <head>
    <!-- 省略了一些内容 -->
  </head>

  <body>
    <div id="planning"></div>

    <script type="text/babel">
      // 省略了一些内容
    </script>
  </body>
</html>

如果你需要更多的帮助,请告诉我。

英文:

I created a mini-scheduling system in react using Ant Design table components. My issue is that when we add around 60 lines (not that crazy right?), the system is really slow (even scrolling horizontally produces a small lag). Like any operation I do takes maybe 5 seconds:

React(搭配Ant Design表格)非常慢:如何优化?

Any idea what I’m doing wrong, and how we can debug these issues?

EDIT I also tried to ad memo and useCallback, but same issue…

Example code:

&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
&lt;title&gt;Planning&lt;/title&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@babel/standalone/babel.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/react@18/umd/react.development.js&quot; crossorigin&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/react-dom@18/umd/react-dom.development.js&quot; crossorigin&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/react-redux@8.0.5/dist/react-redux.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@reduxjs/toolkit@1.9.3/dist/redux-toolkit.umd.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot; https://cdn.jsdelivr.net/npm/dayjs@1.11.7/dayjs.min.js &quot;&gt;&lt;/script&gt;
&lt;script src=&quot; https://cdn.jsdelivr.net/npm/antd@5.5.0/dist/antd.js &quot;&gt;&lt;/script&gt;
&lt;link href=&quot; https://cdn.jsdelivr.net/npm/antd@5.5.0/dist/reset.min.css &quot; rel=&quot;stylesheet&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;planning&quot;&gt;&lt;/div&gt;
&lt;script type=&quot;text/babel&quot;&gt;
const { useContext, useEffect, useRef, useState, memo, useCallback } = React;
const { useDispatch, useSelector, Provider } = ReactRedux;
const { configureStore, createSlice } = RTK;      
const { Button, Form, Input, InputNumber, Popconfirm, Table, Select, Tag, Slider } = antd;
// ***************************
// Store
// ***************************
const stateToSaveReducer = createSlice({
name: &quot;stateToSave&quot;,
initialState: {
// We try to keep everything in a single table, to provide simple copy/paste and visualisation etc...
allSchedules: [
{
columns: [
// subsetOf are list separated with ;, this allows easy import/export to csv/excel/…
{field: &quot;Place&quot;, kind: &quot;subsetOf&quot;, description: &quot;Endroit(s) o&#249; la personne travaille.&quot;, values: [&quot;Place 1&quot;, &quot;Place 2&quot;]},
{field: &quot;Type&quot;, kind: &quot;oneOf&quot;, description: &quot;Type de travail, soit aides soignantes, soit agents service logistique&quot;, values: [&quot;AS&quot;, &quot;ASL&quot;]},
{field: &quot;Pourcentage&quot;, kind: &quot;intBetween&quot;, values: [0, 100], description: &quot;Pourcentage travail.&quot;, marks: [0, 50, 80, 100]},
],
allowedTags: [
{name: &quot;Place 1&quot;},
{name: &quot;Place 2&quot;},
{name: &quot;Morning&quot;},
{name: &quot;Lunch&quot;},
{name: &quot;Meeting 1&quot;},
{name: &quot;Meeting 2&quot;},
{name: &quot;Evening&quot;},
],
nbDays: 3*7,
scheduleAndEmployee: [
{
name: &quot;Alice Montest&quot;,
Place: &quot;Place 1;Place 2&quot;,
Type: &quot;AS&quot;,
Pourcentage: &quot;80&quot;,
days: [
// Just a list of tags, it will be turned later into time etc.
// for now these tags have no meaning.
&quot;Lunch;Meeting 1;Morning;Place1&quot;,
&quot;Evening&quot;,
], 
},
{
name: &quot;Bob Monnomdefam&quot;,
Place: &quot;MAPPA&quot;,
Type: &quot;AS&quot;,
Pourcentage: &quot;100&quot;,
days: [
// Just a list of tags, it will be turned later into time etc.
// for now these tags have no meaning.
&quot;Meeting 2;Morning;Place 1&quot;,
&quot;Evening&quot;,
&quot;Lunch&quot;
], 
}
]
}
]
},
reducers:{
removeEmployee: (state, action) =&gt; {
state.allSchedules[action.payload.idSchedule].scheduleAndEmployee = state.allSchedules[action.payload.idSchedule].scheduleAndEmployee.filter((e,i) =&gt; i != action.payload.key)
},
addEmployee: (state, action) =&gt; {
var t = state.allSchedules[action.payload.idSchedule].scheduleAndEmployee;
t.push({
name: &quot;Employ&#233; &quot; + (t.length+1)
});
},
// Duplicate the last employee, except for name, of course, and days
duplicateLastEmployee: (state, action) =&gt; {
var t = state.allSchedules[action.payload.idSchedule].scheduleAndEmployee;
const {name, days, ...rest} = t[t.length-1];
t.push({...rest,
name: &quot;Employ&#233; &quot; + (t.length+1)
});
},
updateEmployee: (state, action) =&gt; {
var t = state.allSchedules[action.payload.idSchedule].scheduleAndEmployee;
const {key, ...rest} = action.payload.newEmployee;
state.allSchedules[action.payload.idSchedule].scheduleAndEmployee[key] = rest;
},
updateEmployeeDay: (state, action) =&gt; {
var t = state.allSchedules[action.payload.idSchedule].scheduleAndEmployee;
if (!state.allSchedules[action.payload.idSchedule].scheduleAndEmployee[action.payload.key].hasOwnProperty(&quot;days&quot;)) {
state.allSchedules[action.payload.idSchedule].scheduleAndEmployee[action.payload.key].days = [];
}
state.allSchedules[action.payload.idSchedule].scheduleAndEmployee[action.payload.key].days[action.payload.day] = action.payload.dayContent;
}
}
})
const store = configureStore({
reducer: {
stateToSave: stateToSaveReducer.reducer
},
})
const { removeEmployee, addEmployee, duplicateLastEmployee, updateEmployee, updateEmployeeDay } = stateToSaveReducer.actions
const selectorScheduleAndEmployee = (idSchedule, state) =&gt; {
return state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee.map((x, i) =&gt; {return {...x, key:i}})
}
// ***************************
// Main grid
// ***************************
const AddEmployeeButton = ({...props}) =&gt; {
const dispatch = useDispatch();
const [nbEmployee, setNbEmployee] = useState(3);
const handleAdd = useCallback((e) =&gt; {
Array(nbEmployee).fill().map(() =&gt; dispatch(duplicateLastEmployee({idSchedule: props.idSchedule})))
},[nbEmployee, props.idSchedule]);
const handleClick = useCallback(e =&gt; {e.stopPropagation();e.preventDefault()}, []);
return &lt;Button onClick={handleAdd} type=&quot;primary&quot; style={{ marginBottom: 16 }}&gt;
Ajouter &lt;InputNumber min={1} value={nbEmployee} onChange={setNbEmployee} onClick={handleClick} size=&quot;small&quot; /&gt; employ&#233;(e)
&lt;/Button&gt;
};
const ComponentIntBetween = memo(({oldRow, nameField, values, marks, idSchedule, ...props}) =&gt; {
const dispatch = useDispatch();
const valueSelect = useSelector((state) =&gt;
parseInt(state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key][nameField]));
const handleChange = (newValue) =&gt; {
const newEmployee = {...oldRow, [nameField]: newValue.toString()};
dispatch(updateEmployee({idSchedule: idSchedule, newEmployee: newEmployee}));
};
return &lt;Slider
min={values[0]}
max={values[1]}
marks={Object.fromEntries(marks.map((x) =&gt; {return [x, x]}))}
style={{ width: &quot;80%&quot; }}
onChange={handleChange}
value={typeof valueSelect === &#39;number&#39; ? valueSelect : 0}
/&gt;
});
const ComponentSelectFromList = memo(({oldRow, nameField, values, idSchedule, ...props}) =&gt; {
const dispatch = useDispatch();
const valueSelect = useSelector((state) =&gt; state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key][nameField]);
const handleChange = (newValue) =&gt; {
const newEmployee = {...oldRow, [nameField]: newValue};
dispatch(updateEmployee({idSchedule: idSchedule, newEmployee: newEmployee}));
};
return &lt;Select
defaultValue={values[0]}
value={valueSelect}
style={{ width: &quot;100%&quot; }}
bordered={false}
onChange={handleChange}
options={values.map((x) =&gt; {return {value: x, label: x}})}
/&gt;
});
const tagRender = memo((props) =&gt; {
const { label, value, closable, onClose } = props;
const onPreventMouseDown = useCallback((event) =&gt; {
event.preventDefault();
event.stopPropagation();
},[]);
return (
&lt;Tag
onMouseDown={onPreventMouseDown}
closable={closable}
onClose={onClose}
style={{
marginRight: 3,
}}
&gt;
{label}
&lt;/Tag&gt;
);
});
const ComponentSelectSubsetFromList = memo(({oldRow, nameField, values, idSchedule, ...props}) =&gt; {
const dispatch = useDispatch();
const valueSelect = useSelector((state) =&gt; state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key][nameField].split(&quot;;&quot;).filter(element =&gt; element));
const handleChange = (newValue) =&gt; {
const newEmployee = {...oldRow, [nameField]: newValue.join(&quot;;&quot;)};
dispatch(updateEmployee({idSchedule: idSchedule, newEmployee: newEmployee}));
};
return &lt;Select
mode=&quot;multiple&quot;
showArrow
tagRender={tagRender}
value={valueSelect}
style={{ width: &quot;100%&quot; }}
bordered={false}
onChange={handleChange}
options={values.map((x) =&gt; {return {value: x}})}
/&gt;
});
const ComponentDay = memo(({oldRow, day, idSchedule, ...props}) =&gt; {
const dispatch = useDispatch();
const valueSelect = useSelector((state) =&gt; {
if (!state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key].hasOwnProperty(&quot;days&quot;)) {
return []
}
if (state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key].days.hasOwnProperty(day)) {
return state.stateToSave.allSchedules[idSchedule].scheduleAndEmployee[oldRow.key].days[day].split(&quot;;&quot;).filter(element =&gt; element)
} else {
return []
}});
const allowedTags = useSelector((state) =&gt;
state.stateToSave.allSchedules[idSchedule].allowedTags);
const handleChange = (newValue) =&gt; {
dispatch(updateEmployeeDay({idSchedule: idSchedule, key: oldRow.key, day: day, dayContent: newValue.join(&quot;;&quot;)}));
};
return &lt;Select
mode=&quot;multiple&quot;
showArrow
tagRender={tagRender}
value={valueSelect}
style={{ width: &quot;100%&quot; }}
bordered={false}
onChange={handleChange}
options={allowedTags.map((x) =&gt; {return {value: x.name}})}
/&gt;
});
const EditableContext = React.createContext(null);
const EditableRow = memo(({ index, ...props }) =&gt; {
const [form] = Form.useForm();
return (
&lt;Form form={form} component={false}&gt;
&lt;EditableContext.Provider value={form}&gt;
&lt;tr {...props} /&gt;
&lt;/EditableContext.Provider&gt;
&lt;/Form&gt;
);
});
const EditableCell = memo(({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) =&gt; {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
const form = useContext(EditableContext);
useEffect(() =&gt; {
if (editing) {
inputRef.current.focus();
}
}, [editing]);
const toggleEdit = useCallback(() =&gt; {
setEditing(!editing);
form.setFieldsValue({
[dataIndex]: record[dataIndex],
});
},[editing,dataIndex,record]);
const save = async () =&gt; {
try {
const values = await form.validateFields();
toggleEdit();
handleSave({
...record,
...values,
});
} catch (errInfo) {
console.log(&#39;Save failed:&#39;, errInfo);
}
};
let childNode = children;
if (editable) {
childNode = editing ? (
&lt;Form.Item
style={{
margin: 0,
}}
name={dataIndex}
rules={[
{
required: true,
message: `${title} is required.`,
},
]}
&gt;
&lt;Input ref={inputRef} onPressEnter={save} onBlur={save} /&gt;
&lt;/Form.Item&gt;
) : (
&lt;div
className=&quot;editable-cell-value-wrap&quot;
style={{
paddingRight: 24,
}}
onClick={toggleEdit}
&gt;
{children}
&lt;/div&gt;
);
}
return &lt;td {...restProps}&gt;{childNode}&lt;/td&gt;;
});
// Main table
const Antgrid = () =&gt; {
const idSchedule = 0;
const dataSource = useSelector((state) =&gt; selectorScheduleAndEmployee(idSchedule, state));
const customColumns = useSelector((state) =&gt; state.stateToSave.allSchedules[idSchedule].columns);
const nbDays = useSelector((state) =&gt; state.stateToSave.allSchedules[idSchedule].nbDays);
const dispatch = useDispatch()
const defaultColumns = [
{
title: &#39;Nom&#39;,
dataIndex: &#39;name&#39;,
fixed: &#39;left&#39;,
width: 180,
editable: true
}].concat(customColumns.map((c) =&gt; {
// We add the columns like percent of work etc…
// Depending on the type of the column, we display different components
var col = {
title: c.field,
dataIndex: c.field,
width: 180,
};
switch (c.kind) {
case &quot;oneOf&quot;:
return {...col,
render: (_, record) =&gt; {
return &lt;ComponentSelectFromList nameField={c.field} idSchedule={idSchedule} oldRow={record} values={c.values} /&gt;
}
}
break;
case &quot;subsetOf&quot;:
return {...col,
render: (_, record) =&gt; {
return &lt;ComponentSelectSubsetFromList nameField={c.field} idSchedule={idSchedule} oldRow={record} values={c.values} /&gt;
}
}
break;
case &quot;intBetween&quot;:
return {...col,
render: (_, record) =&gt; {
return &lt;ComponentIntBetween nameField={c.field} idSchedule={idSchedule} oldRow={record} values={c.values} marks={c.marks ? c.marks : []}/&gt;
}
}
break;
default:
return col
}
})).concat(Array.from({length: nbDays}, (x,i) =&gt; {
// We add the actual working days columns
return {
title: &#39;Day&#39;,
dataIndex: [&#39;days&#39;, i],
width: 150,
render: (_, record) =&gt; {
return &lt;ComponentDay day={i} idSchedule={idSchedule} oldRow={record} /&gt;
}
}
})).concat([{
title: &#39;Operations&#39;,
dataIndex: &#39;Operations&#39;,
width: 100,
render: (_, record) =&gt; (
dataSource.length &gt;= 1 ? (
&lt;Popconfirm title=&quot;Sure to delete?&quot; onConfirm={() =&gt; dispatch(removeEmployee({idSchedule: idSchedule, key: record.key}))}&gt;
&lt;a&gt;Delete&lt;/a&gt;
&lt;/Popconfirm&gt;
) : null),
}]);
const handleSave = (row) =&gt; {
dispatch(updateEmployee({idSchedule: idSchedule, newEmployee: row}))
};
// We override defaults table elements to make them editable
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
const columns = defaultColumns.map((col) =&gt; {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) =&gt; ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
};
});
// const columns = defaultColumns;
return (
&lt;div&gt;
&lt;Table
size=&quot;small&quot;
dataSource={dataSource}
columns={columns}
sticky
pagination={false}
scroll={{ x: &quot;100%&quot; }}
components={components}
/&gt;
&lt;AddEmployeeButton idSchedule={idSchedule}/&gt;
&lt;/div&gt;
);
};
function App() {
return (&lt;&gt;
&lt;h1&gt;Planning&lt;/h1&gt;
&lt;Antgrid/&gt;
&lt;/&gt;)
};
const container = document.getElementById(&#39;planning&#39;);
const root = ReactDOM.createRoot(container);
root.render(
&lt;React.StrictMode&gt;
&lt;Provider store={store}&gt;            
&lt;App /&gt;
&lt;/Provider&gt;
&lt;/React.StrictMode&gt;
)
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

答案1

得分: 1

  1. memo() 应用于所有单元格
  2. useCallback 应用于所有回调函数
  3. useMemo() 应用于所有可能更改的样式和对象
  4. 非常重要(仅此更改可能足够?):像这样设置 shouldCellUpdate
render: (_, record) =&gt; {
return &lt;EditableCell nameField={&quot;name&quot;} idSchedule={idSchedule} oldRow={record} /&gt;
},
// https://github.com/ant-design/ant-design/issues/23763
shouldCellUpdate: (record, prevRecord) =&gt; !shallowEqual(record, prevRecord)

仍然存在一些滞后,但可能只有半秒,所以我可以接受。我还将第一个可编辑文本区域更改为另一个单元格区域,这样我就不需要担心是否存在 shouldCellUpdate 用于此自定义行。

英文:

Ok, I found a solution to the refresh problem (but not to the long creation time… but that time is only once so I can live with it for now). The idea is to combine:

  1. memo() on all cells
  2. useCallback on all functions that are callbacks
  3. useMemo() on all styles and objects that might change
  4. and very importantly (this only change might even be enough?): set shouldCellUpdate like in:
render: (_, record) =&gt; {
return &lt;EditableCell nameField={&quot;name&quot;} idSchedule={idSchedule} oldRow={record} /&gt;
},
// https://github.com/ant-design/ant-design/issues/23763
shouldCellUpdate: (record, prevRecord) =&gt; !shallowEqual(record, prevRecord)

there is still a bit of lag, but it’s maybe half a second so I can live with that. I also changed the first editable text zone into another cell zone, this way I don’t need to worry if shouldCellUpdate exists for this custom row.

huangapple
  • 本文由 发表于 2023年5月22日 15:29:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303884.html
匿名

发表评论

匿名网友

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

确定