Я пытаюсь вставить новые элементы в массив и обновить базу состояний в массиве, но проблема после обновления состояния. Он не отображается в компоненте.
- примечание: я не совсем уверен, как использовать сращивание. (Я хотел, чтобы функция
handleClick
добавляла новый элемент под выбранным элементом, но, похоже, мне это тоже не удалось.) - примечание 2: я тоже пробовал
setstate((pre) => { pre.splice(index + 1, 0, { id: 3, text: "xxx", autoFocus: true }); return pre; });
, но тоже не сработало.
import React, { useState } from "react";
import "./styles.css";
export default function App() {
let elements = [
{ id: 0, text: "first", autoFocus: true },
{ id: 1, text: "second", autoFocus: true },
{ id: 2, text: "third", autoFocus: true }
];
const [state, setstate] = useState(elements);
function handChange(e) {
if (e.keyCode == 13) {
const x = state;
const index = x.findIndex((item) => item.id == e.target.id);
//i'm using autoFocus to move the focus (I-beam pointer) to the nex field.
//but i still get errors with it
// e.map((item) => Object.assign(item, { autoFocus: false }));
x.splice(index + 1, 0, { id: 3, text: "xxx", autoFocus: true });
console.log(state); // you can see this update probarly
setstate(x); // but when I update state sometimes it don't render othertimes it take a while before render.
}
}
return (
<div className="App">
{state.map((e) => (
// when I say it don't render I mean the e value don't get updated.
<div
focus={e.focus}
contentEditable="true"
id={e.id}
onKeyUp={handChange}
>
{e.text}
</div>
))}
</div>
);
}
на codeandbox