fix(striker-ui): generate message keys only when necessary in MessageGroup

main
Tsu-ba-me 2 years ago
parent 3beca2f40b
commit ca36fe21c0
  1. 32
      striker-ui/components/MessageGroup.tsx

@ -1,6 +1,7 @@
import { import {
forwardRef, forwardRef,
useCallback, useCallback,
useEffect,
useImperativeHandle, useImperativeHandle,
useMemo, useMemo,
useState, useState,
@ -36,23 +37,7 @@ const MessageGroup = forwardRef<
}, },
ref, ref,
) => { ) => {
const { keys: messageKeys } = useMemo( const [messageKeys, setMessageKeys] = useState<string[]>([]);
() =>
Array.from({ length: count }).reduce<{
keys: string[];
}>(
(previous) => {
const { keys } = previous;
keys.push(uuidv4());
return previous;
},
{ keys: [] },
),
[count],
);
const [messages, setMessages] = useState<Array<Message | undefined>>([]); const [messages, setMessages] = useState<Array<Message | undefined>>([]);
const setMessage = useCallback((index: number, message?: Message) => { const setMessage = useCallback((index: number, message?: Message) => {
@ -94,6 +79,19 @@ const MessageGroup = forwardRef<
[defaultMessageType, messages, messageKeys], [defaultMessageType, messages, messageKeys],
); );
useEffect(() => {
setMessageKeys((previous) => {
const result = [...previous];
const diff = count - result.length;
if (diff > 0) {
result.push(...Array.from({ length: diff }, () => uuidv4()));
}
return result;
});
}, [count]);
useImperativeHandle(ref, () => ({ setMessage }), [setMessage]); useImperativeHandle(ref, () => ({ setMessage }), [setMessage]);
return <>{messageElements}</>; return <>{messageElements}</>;

Loading…
Cancel
Save