简体   繁体   English

ReactJS 添加到 Object 是 State

[英]ReactJS Add to Object that is a State

hoping this is a simple answer but it's racking my brain.希望这是一个简单的答案,但它让我绞尽脑汁。 Let's say I have the following React pseudocode:假设我有以下 React 伪代码:

const [cats, setCats] = useState({});

console.log(cats);

cats = {

}

I am trying to add uh cats to the cats object via a button click.我正在尝试通过单击按钮将呃猫添加到猫 object 中。 I'm not sure what the exact code should be, as any guess I have so far doesn't work.我不确定确切的代码应该是什么,因为到目前为止我的任何猜测都行不通。 The closest i've gotten is the following pseudo code:我得到的最接近的是以下伪代码:

heres the object i'm sending in:这是我要发送的 object:

{
Bruto:{
     id : 2,
     name: 'Bruto',
     }
}

const addCat (e, catName) => {
setCats(...cats, event.target.value);
}

<input onKeyDown={e=>addCat(e,catDetails)}></input>

Which all it does is just add the word typed into the input as cats, but doesn't add it structurally.它所做的只是将输入到输入中的单词添加为猫,而不是在结构上添加它。 Ideally what i'd want is the following:理想情况下,我想要的是以下内容:

1. Check to see if catDetails exists in cats
2. If not, add the catDetails.id to the object 
3. Add catDetails.name to cats[catDetails.id] such as the object should be:
    cats{
       0: {
         name: "Heathcliff"
        }
       2: {
         name: "Bruto"
        }
      }

Hoping someone can help.希望有人可以提供帮助。 Below is the code I have so far下面是我到目前为止的代码

const addTag = (event, cats) => {
    if (event.key === "Enter"){
     setCats(...cats, event.target.value)
    }
   console.log(cats);
  }

Thank you!谢谢!

You can do:你可以做:

setCats( prevCats => {...prevCats, {id:2, name:"Bruto"})

or even better: you can use useReducer instead of useState甚至更好:您可以使用useReducer而不是useState

EDIT: just to be a bit more clear, instead of passing the new state to setCats you pass a function which will automatically receive the previous state and whatever is returned will be used as the new state. EDIT: just to be a bit more clear, instead of passing the new state to setCats you pass a function which will automatically receive the previous state and whatever is returned will be used as the new state.

You'll probably find an array easier to use.您可能会发现数组更易于使用。

Have one state (an array) for all your cat objects, and have another (string) for the cat you're adding in the input, and then update the cats array with the current cat if it's not been found.为您的所有猫对象设置一个 state (一个数组),并为您在输入中添加的猫设置另一个(字符串),然后使用当前猫更新猫数组(如果未找到)。

 const { useEffect, useState } = React; function Example() { // Initialise cat states const [ cats, setCats ] = useState([]); const [currentCat, setCurrentCat] = useState(''); // Updates the currentCat state when the input changes function handleChange(e) { setCurrentCat(e.target.value); } // First find out if the cat name we're entering exists // in the cats array. If it doesn't, add it function addCat(e) { const found = cats.find(cat => cat.name === currentCat); if (.found) { setCats([..,cats: { id. cats,length + 1: name; currentCat } ]). } } useEffect(() => console,log(cats); [cats]); return ( <div> <input type="text" onChange={handleChange} /> <button type="button" onClick={addCat} >Add cat </button> </div> ); }. ReactDOM,render( <Example />. document;getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

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

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