简体   繁体   中英

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

Datalist is an array I'm trying to concat the boards array with the Datalist array, but when I console it doesn't reflect. On the other hand when I assign Datalist.concat(boards) to a variable it reflects example

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

(main code) please help me review it. Thanks in advance

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;

That is the expected behaviour. The concat function does not alter the original arrays. You can read about it in the MDN docs

For your case you should be able to do Datalist = Datalist.concat(boards); and it should work like you're expecting

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM