简体   繁体   English

无法使用表单 onSubmit React 更新 State

[英]Cannot Update State with Form onSubmit React

I have a component with a list of components.我有一个带有组件列表的组件。 I have an initial cardlist which gets populated as the list in my component.我有一个初始卡片列表,它被填充为我的组件中的列表。 Each time I submit the form I want to add a new component, but I can't get it to update even though my cardlist array gets a new card.每次我提交表单时,我都想添加一个新组件,但即使我的卡片列表数组获得了一张新卡片,我也无法更新它。 What do I do?我该怎么办?

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>
    );
}

Never modify state in React directly.切勿直接在 React 中修改 state。 Instead, copy the values of the old array into a new one.相反,将旧数组的值复制到新数组中。 Also, you should use the old state ( list ) and not your cardlist variable which is just used for initializing the state.此外,您应该使用旧的 state ( list ) 而不是用于初始化 state 的cardlist变量。 In ES6 you can simply do在 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();
}

EDIT: I just saw that you are also not using state for the imgname and imgurl variable, so this answer should work but fill in empty strings for the new values.编辑:我刚刚看到您也没有将 state 用于imgnameimgurl变量,所以这个答案应该有效,但为新值填写空字符串。 Everything that changes in a component should useState :组件中的所有更改都应该useState

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

Also, for controlled inputs, set the value from state to avoid inconsistencies:此外,对于受控输入,从 state 设置值以避免不一致:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM