反应钩子。同时从多个孩子更新父状态

时间:2020-10-31 10:50:33

标签: javascript reactjs react-native asynchronous async-await

我当前情况的描述:

我正在开发一个销售书籍的应用程序,并且正在使用React Context在屏幕之间共享状态。当我进入书本屏幕时,我有两个按钮(自定义子组件)“添加到购物车”和“保存”,在安装时,它们会在我的数据库中获取各自的初始状态(分别添加到购物车或保存)。 / p>

问题

当“添加到购物车”按钮从数据库中获取其初始状态时,它将更新其父状态 通过作为道具接收的回调实现“ currentBookData”。

其他按钮也一样。

这是我的图书屏幕的代码:

  function BookScreen(props) { // 
       const [bookData, setBookData] = useState(props.params.selectedBookData);


       const handleButtonAddToCartLoad = (isAddedToCart) => {
            const {currentUser} = props; // provided by the context

           // !!!!!!!!!!!!!!!!!!!!!!!
           const newBookData = { ...bookData, isAddedToCart };
           setBookData(newBookData);

           currentUser.addVisitedBook(newBookData.id, newBookData); // Update the book in the map of visited books
       }


       const handleButtonSaveLoad = (isSaved) => {
           const {currentUser} = props; // provided by the context

           // !!!!!!!!!!!!!!!!!!!!!!!
           const newBookData = { ...bookData, isSaved };
           setBookData(newBookData);

           currentUser.addVisitedBook(newBookData.id, newBookData); // Update the book in the map of visited books
       }
        


       useEffect(() => {
            // When the screen mounts, update the book data if it wasn't fetched previously
            (async () => {
                const {currentUser} = props; // provided by the context

                if(!currentUser.getVisitedBook(bookData.id)) {

                   // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                   const newBookData = await db.getBook(bookData.id); 

                   // Add the book to the visited books of list
                   currentUser.addVisitedBook(newBookData.id, newBookData );
                }
            })();
       }, []);


       return (
             <View>
                ...
                <AddToCartButton bookId={bookData.id} onLoad={handleButtonAddToCartLoad } />
                <SaveButton bookId={bookData.id} onLoad={handleButtonSaveLoad} />
             </View>
       )

         
  }

  export default withCurrentUser(BookScreen); // <------ It consumes the context where I have a Map with all the data which has been downloaded from the DB. Just to avoid unnecessary requests.

正如您在阅读代码后可以想象的那样,我正在使用React提供的标准标准钩子更新状态。发生的事情是更新是同时出现的,因此状态不是“合并”的,它总是上一次更新的状态:

    {
        id: "bookId",
        title: "bookTitle",
        isAddedToCart: false,
    }

    {
        id: "bookId",
        title: "bookTitle",
        isSaved: true,
    }

有时

   {
        id: "bookId",
        title: "bookTitle",
    }
    

但从来没有我需要的东西

    {
        id: "bookId",
        title: "bookTitle",
        isAddedToCart: false,
        isSaved: true,
    }

任何想法如何使用钩子解决这个问题?

0 个答案:

没有答案