简体   繁体   English

自定义钩子中的 useEffect 不会在删除时重新呈现

[英]useEffect within a custom hook doesn't rerender on delete

I am trying to use hooks and implement a custom hook for handling my data fetching after every update I send to the API.我正在尝试使用钩子并实现一个自定义钩子,以便在我发送到 API 的每次更新后处理我的数据获取。

My custom hook, however, doesn't fire on change like I want it too.然而,我的自定义钩子不会像我想要的那样在变化时触发。 Delete has to be clicked twice for it to rerender.必须单击删除两次才能重新渲染。 Note: I removed some functions from this code as they don't pertain to the question.注意:我从此代码中删除了一些函数,因为它们与问题无关。

    import React, { useState, useEffect } from "react"
    import {Trash} from 'react-bootstrap-icons'
    import InlineEdit from 'react-ions/lib/components/InlineEdit'

    function Board(){
        const [render, setRender] = useState(false)
        const [boards, setBoards] = useState([]);
        const [isEditing, setEdit] = useState(false)
        const [value, setValue] = useState("")
        const[newValue, setNewValue] = useState("")
        const [error, setError] = useState("")

        function useAsyncHook(setState, trigger) {
            const [result] = useState([]);
            const [loading, setLoading] = useState("false");
            useEffect(() => {
                async function fetchList() {
                    try {
                        setLoading("true");
                        const response = await fetch(
                            `http://localhost:8080/api/boards`
                        );
                        const json = await response.json();
                        setState(json)
                    } catch (error) {
                        //console.log(error)
                        setLoading("null");
                    }
                }
            fetchList()
            }, [trigger]);

            return [result, loading];
        }

        useAsyncHook(setBoards, render)

        const handleDelete = (id) => {
            console.log("delete clicked")
            setLoading(true);
            fetch(`http://localhost:8080/api/boards/` + id, {
                method: "DELETE",
                headers: {
                    "Content-Type": "application/json"
                },
            })
            setRender (!render)
        }

       return(
        <div>
            <ul>

                {boards.map(board => (
                <li key={board.id}>
                        <InlineEdit value={board.size} isEditing={isEditing} changeCallback={(event)=>handleSave (event, board.id)} />
                        <Trash onClick={()=>handleDelete(board.id)}/>
                    </li>
            </ul>
        </div>
        );

    }

    export default Board

OPTION 1:选项1:

Maybe you wanna have a hook that tells you when to fetch the board, right?也许你想要一个钩子来告诉你什么时候拿板子,对吧? For example:例如:

const [auxToFetchBoard, setAuxToFetchBoard] = useState(false);

Then, in a useEffect you execute the function fetchBoard everytime that hook changes:然后,在useEffect你执行函数fetchBoard每次那个勾变化:

useEffect(fetchBoard, [auxToFetchBoard]);

Finally, in your handleDelete function, if your delete request returns correctly, you have to update auxToFetchBoard .最后,在您的handleDelete函数中,如果您的删除请求正确返回,您必须更新auxToFetchBoard Something like this:像这样的东西:

const handleDelete = (id) => {
    setIsLoading(true);
    setError("");

    fetch(yourURL, yourOptions)
        .then(res => {
            // check if response is correct and
            setIsLoading(false);
            setAuxToFetchBoard(!auxToFetchBoard);
        })
        .catch(() => {
            setIsLoading(false);
            setError("Error while deleting stuff");
        });
};

Note: I changed the names of isLoading and setIsLoading because they are more explicit.注意:我更改了isLoadingsetIsLoading的名称,因为它们更明确。

OPTION 2:选项 2:

Instead of fetching the board again and again, you can update your board (in this case your code would be in 8th line inside the handleDelete function).您可以更新您的电路板,而不是一次又一次地获取电路板(在这种情况下,您的代码将位于handleDelete函数内的第 8 行)。

Hope it helps.希望能帮助到你。

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

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