Arrays 使用React钩子向对象内的数组添加数据
我不知道如何在React中使用setState by hook将数组数据添加到对象内的数组列表中。有人能帮我吗? 下面是我的代码,每次我登录控制台时,它总是返回空数组Arrays 使用React钩子向对象内的数组添加数据,arrays,reactjs,immutability,react-hooks,Arrays,Reactjs,Immutability,React Hooks,我不知道如何在React中使用setState by hook将数组数据添加到对象内的数组列表中。有人能帮我吗? 下面是我的代码,每次我登录控制台时,它总是返回空数组 import React, { useState } from 'react'; const Main = props => { const [state, setState] = useState({ noteArray: [], noteText: '', }); const addNo
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
}
基本上,您所做的错误是覆盖了您的数组,而不是向其添加新的值。您可以使用以下方法轻松完成此操作:-
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: [...state.noteArray, x]});
console.log(state.noteArray);
}
}
.......................the rest of code
}
你的代码,陷入无限循环,下面是你的代码one@ukiyakimura你是想重置你的数组还是想添加到数组中?@solanki。。。你能解释一下这将如何进入一个无限循环吗?已经在本地测试过了,我正在尝试将其附加到@yashgadle上。我如何使用setState?强制状态立即更新,它仍然不会更改值,直到组件首先被重新渲染@亚什·盖德尔