使用React Hook在对象内部的Array中添加数据

时间:2019-04-14 05:29:51

标签: arrays reactjs immutability react-hooks

我困惑如何在React中使用setState通过钩子将数组数据添加到对象内的数组列表中。有人可以帮我吗? 下面是我的代码,每次我在控制台日志中总是返回空数组。

import React, { useState } from 'react';

const Main = props => {
  const [state, setState] = useState({
    noteArray: [],
    noteText: '',
  });


  const addNote = () => {
    if(state.noteText){
      var d = new Date();
      let x = {
        'date': d.getFullYear() + 
        "/" + (d.getMonth() + 1 ) +
        "/" + d.getDate(),
        'note': state.noteText
      }

      setState({...state, noteArray: x});

      console.log(state.noteArray);
    }
  }

   .......................the rest of code
}

2 个答案:

答案 0 :(得分:-1)

请在下面找到工作代码!

import React, { useState } from 'react';

export default (props) => {
  const [state, setState] = useState({
    noteText: 'sample',
    noteArray: []
  });


  const addNote = () => {
    if(state.noteText){
      var d = new Date();
      let x = {
        'date': d.getFullYear() + 
        "/" + (d.getMonth() + 1 ) +
        "/" + d.getDate(),
        'note': state.noteText
      }
      setState({...state, noteArray: [x]});

      console.log(state);
    }
  }

  return (
    <div>
      <h1>Hello {JSON.stringify(state)}!</h1>
      <button onClick={()=> addNote()}>Click To Add</button>
    </div>
  );
}

WORKING DEMO LINK

DOC

答案 1 :(得分:-1)

基本上,您在做什么错是在覆盖数组而不是向其添加新值。您可以使用以下代码轻松完成此操作:-

def size_splitter(array, size)
  array.partition { |string| string.size == size }.map(&:sort) 
end