使用React状态钩子创建了空数组

344 阅读1分钟

我使用React状态钩子创建了空数组,数组开始是空的,我有3个函数(添加到数组),(删除数组的最后一个元素)和另一个函数来清空数组。这些函数似乎是有效的,因为我在控制台中记录了结果。但是当我想把数组打印在一个段落上时,数组就不显示了。谁能给我一些反馈? 谢谢。

代码如下

import './counter.css';
import { useState } from 'react';

export default function HandleArray() {
  const [inicial, handler] = useState([]);

  function addElement(element) {
    inicial.push('ok');
    handler(inicial);
    console.log(inicial);
  }
  function removeElement() {
    inicial.pop();
    handler(inicial);
    console.log(inicial);
  }
  function reset() {
    inicial.length = 0;
    handler(inicial);
    console.log(inicial);
  }

  return (
    <div className='card text-bg-light border-success mb-3'>
      <div className='card-header'>Welcome</div>
      <div className='card-body'>
        <h5 className='card-title'>Manipulate the array</h5>
        <button type='button' className='btn btn-dark ' onClick={addElement}>
          Insert Element
        </button>
        <button
          type='button'
          className='btn btn-danger'
          onClick={removeElement}
        >
          Remove Element
        </button>
        <button type='button' className='btn btn-warning' onClick={reset}>
          Reset array
        </button>
        
        
        //log the array 
        
        <p className='card-text'>{inicial}</p>
      </div>
    </div>
  );
}