javascript 如何更新嵌套数组?

dba5bblo  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(194)

我有一个数组。我还有contenteditable div。当我编辑div时,我需要更新数组。arraywords是redux状态

const arrayWords = [
   [
       ["Hello",["Lello","Helli","Tello","Dello","Həll"]],
       [" ",[]],
       ["guys", ["guya","rus","göy","kurs","suyu"]]]
]

我的React组件

const [content, setContent] = useState();
  useEffect(() => {
    setContent(element); // element is word
  }, [element]);

  const handleChange = (evt) => {
    setContent(evt.target.value);
    console.log(index);
  };

  return <ContentEditable html={content} className="editable-div" onChange={handleChange} />;

例如,我需要数组返回hi,而不是hellomen,而不是guys

const arrayWords = [
   [
       ["Hi",["Lello","Helli","Tello","Dello","Həll"]],
       [" ",[]],
       ["men", ["guya","rus","göy","kurs","suyu"]]]
]

这是子元素。父元素:

<Result element={i[0]} item={item} index={order} />
sczxawaw

sczxawaw1#

在handleChange函数中,您可以通过复制原始数组并用新单词替换相应单词来更新数组:

const handleChange = (evt) => {
  const newContent = evt.target.value;
  const newWords = arrayWords.map((sentence) =>
    sentence.map((wordData) =>
      wordData[0] === element ? [newContent, wordData[1]] : wordData
    )
  );
  dispatch(setWords(newWords)); // setWords is the Redux action to update the state
  setContent(newContent);
};

相关问题