简体   繁体   English

如何在对象上设置useState数据

[英]how to set useState data on an object

I'm trying to set an object with useState, however I only get in initial value, can anyone see what I'm doing wrong, the object in question is setWishlist, 我正在尝试使用useState设置一个对象,但是我只获得初始值,任何人都可以看到我做错了,有问题的对象是setWishlist,

const CenterModal = props => {
  const [modalData, setModalData] = useState({
    color: 'red',
    title: '',
    description: ''
  });

const onSubmit = e => {
    e.preventDefault();
    props.onHide();
    const wishlistData = {
      color: modalData.color,
      title: modalData.title,
      description: modalData.description,
    };

    //Pass the data to Wishlist component
    props.wishlistdata(wishlistData);
    console.log('wishlistData: ', wishlistData);
  };
 }

const Wishlist = props => {

    const [wishList, setWishList] = useState({
    color: 'red',
    title: '',
    description: ''
  });

  const onWishListDataReceived = wishListData => {
    setWishList({
      color: wishListData.color
      title: wishListData.title,
      description: wishListData.description,
    });
    console.log('wish list data is: ', wishList);
  };

return(    
   <CenterModal
      title="EDIT WISHLIST ITEM"
      show={modalShow}
      onHide={modalClose}
      wishlistdata={e => onWishListDataReceived(e)}
   />
 )
}

in the console.log I only get the initial state, 在console.log中我只得到初始状态,

I think the issue is because whenever you invoke the function you are not passing in an object with correct information as an argument. 我认为问题在于,无论何时调用函数,都不会传入具有正确信息的对象作为参数。 it is trying to access properties on the place holder so the correct info has to be passed when invoked, or it will just be undefined. 它试图访问占位符上的属性,因此在调用时必须传递正确的信息,否则它将是未定义的。 Also don't think you need the square brackets around the keys. 也不要认为你需要键周围的方括号。

I figured it out, Just for future reference, 我想通了,仅供将来参考,

I had to use useEffects like the following 我不得不使用如下的useEffects

useEffect(() => {
    console.log('wishlistdata is: ', wishList);
  }, [wishList]);

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

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