我对如何在 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
}
基本上你做错的是你覆盖了你的数组,而不是给它添加新的值。您可以使用这个轻松做到这一点:-
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
}