我如何将一个数组与另一个使用本地存储的数组连接起来

How do i concat an array with a different array which uses of local storage

Datalist 是一个数组,我试图用 Datalist 数组 concat boards 数组,但是当我控制台时它没有反映。另一方面,当我将 Datalist.concat(boards) 分配给一个变量时,它反映了 example

const newArr = Datalist.concat(boards);
console.log(newArr)

(主要代码)请帮我审阅一下。提前致谢

import React, { useState, useEffect } from 'react';
import Modal from './Modal';
import { Datalist } from '../Data/Boards';

function Boards() {
  const [boards, setboards] = useState(JSON.parse(localStorage.getItem('boards')) || []);
  const [title, settitle] = useState('');
  localStorage.setItem('boards', JSON.stringify(boards));

  Datalist.concat(boards);
  console.log(Datalist);

  const handleChange = (e) => {
    settitle(e.target.value);
  };
  const handleSubmit = () => {
    if (title.length === 0) {
      return;
    }
    setboards((prev) => [...prev, title]);
  };
  return (
    <div>
      <ul id="boards">
        <BoardList boards={boards} />
      </ul>
      <Modal title={title} handleChange={handleChange} handleSubmit={handleSubmit} />
    </div>
  );
}
function BoardList({ boards }) {
  const history = useHistory();
  return (
    <>
      {boards.map((board, index) => (
        <li
          key={index}
          onClick={() => {
            history.push('./workspace');
          }}
        >
          <h3>{board}</h3>
        </li>
      ))}
    </>
  );
}
export default Boards;

这是预期的行为。 concat 函数不会改变原始数组。您可以在 MDN docs

中阅读相关信息

对于您的情况,您应该能够做到 Datalist = Datalist.concat(boards); 并且它应该像您期望的那样工作