简体   繁体   中英

New property value not being rendered

Im rendering an array of objects, then I'm trying to add a new property to it via a function, but that new property value does not render. When I console log the object I can see that the property and the new value are there. That new property is tag . I assume this has something to do with e.preventDefault() . How can I fix this?

const addTag = (e,id) => {
  e.preventDefault()
  let text = e.target.tag.value
  let obj = stu.find(x => x.id === id)
  obj.tag = text
  console.log(obj)
}

  return (
    <div className="App">
      {stu.map((student, id) => (
          <div key={id}>
            <p>{student.email}</p>
            <p>{student.firstName}</p>
            <p>{student.tag}</p>
            <form onSubmit={(e) => addTag(e, student.id)}>
              <input type="text" id="tag"/>
              <button type="submit">Submit</button>            
            </form>
          </div>
      ))}
    </div>
  );
}

Your state variable is an array. Modifying objects in that array, (or even adding/removing elements entirely) will not cause react to re-render. The reference to the array must change. One easy way to do this is to copy the elements to a new array:

const addTag = (e,id) => {
  e.preventDefault()
  let text = e.target.tag.value
  let obj = stu.find(x => x.id === id)
  obj.tag = text
  setStu([...stu])
}

*you may run into issues since you're keying only on the element index. Consider changing your key value as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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