Reactjs 我试图将数据推入react中useState中定义的数组,但数据并没有被推入数组
我试图将一些数据推送到useState中定义的数组中,但数据没有被推送到数组中 //下面是代码Reactjs 我试图将数据推入react中useState中定义的数组,但数据并没有被推入数组,reactjs,react-hooks,Reactjs,React Hooks,我试图将一些数据推送到useState中定义的数组中,但数据没有被推送到数组中 //下面是代码 const [formData, setFormData] = useState({ name: "", technology: [], description: "", technoText: '' }); const { name, description, technoText, technology } = formD
const [formData, setFormData] = useState({
name: "",
technology: [],
description: "",
technoText: ''
});
const { name, description, technoText, technology } = formData;
const onChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const onAdd = (e) => {
e = e || window.event;
const newElement = { id: uuid.v4(), value: technoText }
if(e.keyCode === 13){
setFormData({...formData, technology: currentArray => [...currentArray, newElement]});
console.log(newElement);
console.log('this is technology', technology)
}
}
//newElement的数据正在控制台中记录,但未在阵列技术中推送。将
技术
键设置为阵列
,而不是函数或使用函数使用状态
:
const [formData, setFormData] = useState({
technology: []
});
const { name, description, technoText, technology } = formData;
const onChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const onAdd = e => {
e = e || window.event;
const newElement = { id: uuid.v4(), value: technoText };
if (e.keyCode === 13) {
setFormData({ ...formData, technology: [...technology, newElement] });
// v You defined the `technology`'s value as a function
// setFormData({...formData, technology: currentArray => [...currentArray, newElement]});
// I think you ment using a functional useState like so:
setFormData(prevState => ({
...formData,
technology: [...prevState.technology, newElement]
}));
// Or more like
setFormData(({ technology: currentArray }) => ({
...formData,
technology: [...currentArray, newElement]
}));
}
};
什么?更改注释中提到的
currentArray=>[…currentArray,newElement]}