无法使用表单onSubmit React更新状态



我有一个带有组件列表的组件。我有一个初始的卡片列表,它被填充为我的组件中的列表。每次我提交表单时,我都想添加一个新组件,但即使我的卡片列表数组得到了一张新卡片,我也无法更新它。我该怎么办?

import { Card } from "./Card";
export function Body() {
let imgname = "";
let imgurl = "";
let cardlist = [
{
name: "ca122t1",
url: "https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg"
},
{
name: "cat2",
url: "https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg"
}
]
const [list, setList] = React.useState(cardlist);


function handleName(event) {
imgname = event.target.value;
}
function handleURL(event) {
imgurl = event.target.value;
}
function handleSubmit(e) {
let imgToAdd = {name: imgname, url: imgurl}
cardlist.push(imgToAdd)
setList(cardlist)
e.preventDefault()
}
return (
<div>
<form onSubmit={handleSubmit}>
<label>Name</label>
<input type="text" onChange={handleName}/>
<label>Image URL</label>
<input type="text" onChange={handleURL}/>
<input type="submit" value="Submit"/>
</form>
<ul>
{list.map((item) => (
<Card name={item.name} url={item.url}></Card>
))}
</ul>
</div>
);
}

永远不要直接修改React中的状态。相反,将旧数组的值复制到新数组中。此外,您应该使用旧状态(list(,而不是仅用于初始化状态的cardlist变量。在ES6中,您可以简单地进行

function handleSubmit(e) {
// copy the elements of list into a new array and add the new card
setList([...list, {name: imgname, url: imgurl}]);
e.preventDefault();
}

编辑:我刚刚看到您也没有为imgnameimgurl变量使用state,所以这个答案应该有效,但为新值填充空字符串。组件中发生变化的所有内容都应useState:

const [imgname, setImgname] = useState("");
function handleName(event){
setImgname(event.target.value)
}

此外,对于受控输入,从状态设置值以避免不一致:

<input type="text" onChange={handleName} value={imgname} />

最新更新