繁体   English   中英

在反应中触发来自子级的父级 API 调用

[英]Trigger parent API call from child in react

在我的父母(Feed)中,我显示了一个帖子列表:

function Feed() {

    const [posts, setPosts] = useState(null);

    useEffect(() => {
        const fetchPosts = async () => {
            try {
                const result = await axios({
                ...
                });
    
                setPosts(result.data);
                ...
            } catch (e) {
                ...
            }
        };
        fetchPosts();
    }, []);

    return (
        ...
            {posts &&
                <div>
                    <PostCompose />                              // post creation
                    {posts.map((item, index) =>                  // map existing posts
                        <Post key={item._id} {...item} />)}      
                </div>
            }
        ...
    )
}

孩子(PostCompose)可以创建一个帖子:

function PostCompose() {

    const [text, setText] = useState('');

    const createPost = async () => {
        try {
            const result = await axios({
                ...
            })
            ...
        } catch (e) {
            ...
        }
    }

    const handleTextChange = (e) => {
        setText(e.target.value);
    }

    return (
        ...
        <textarea onChange={handleTextChange} />
        <button onClick={createPost}>Post</button>
        ...
    )
}

PostCompose 组件向后端发出请求以创建新帖子,但是如何触发 Feed 刷新以拉取新的帖子列表?

我觉得我的方法可能需要一些工作,任何帮助都会很棒,因为我对 React 很陌生。 谢谢。

一种方法是将您的fetchPosts函数从效果回调中取出,使用useCallback挂钩来记忆它。 您现在可以在Feed组件挂载时调用fetchPosts并将其提供给您的PostCompose组件,就像我在这里使用afterPostCreated所做的那样:

function Feed() {
    const [posts, setPosts] = useState(null);

    const fetchPosts = useCallback(async () => {
        try {
            const result = await axios({
                // ...
            });

            setPosts(result.data);
            // ...
        } catch (e) {
            // ...
        }
    }, []);

    useEffect(() => {
        fetchPosts();
    }, [fetchPosts]);

    return (
        posts && (
            <div>
                <PostCompose afterPostCreated={fetchPosts} /> // post creation
                {posts.map(
                    (
                        item,
                        index // map existing posts
                    ) => (
                        <Post key={item._id} {...item} />
                    )
                )}
            </div>
        )
    );
}

然后在帖子成功创建后,只需在PostCompose组件中调用该回调:

function PostCompose({ afterPostCreated }) {
    const [text, setText] = useState('');

    const createPost = async () => {
        try {
            const result = await axios({
                // ...
            });
            // ...

            if (afterPostCreated) {
                afterPostCreated();
            }
        } catch (e) {
            // ...
        }
    };

    const handleTextChange = (e) => {
        setText(e.target.value);
    };

    return (
        <>
            <textarea onChange={handleTextChange} />
            <button onClick={createPost}>Post</button>
        </>
    );
}

暂无
暂无

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

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