从子组件重新渲染 useEffect

时间:2021-02-20 11:25:15

标签: reactjs

const CompleteDriverInfo = () => {
  const [DriverInfo, setDriverInfo] = useState([]);
  useEffect(async () => {
    await setDriverInfo(await GetFetch('driver'));
  }, []);
  return (
    <div>
      <Link to='/adddriver'>
        <button className='btn btn-primary'>Add Driver</button>
      </Link>
      {DriverInfo.map((EachDriver) => (
        <EachDriverInfo EachDriver={EachDriver} />
      ))}
    </div>
  );
};

const EachDriverInfo = ({ EachDriver }) => {
  const DeleteDriver = (e) => {
    POST(
      'deletedriver',
      {
        CustomerName: EachDriver.CustomerName,
      },
      e
    );
  };
  return (
    <>
      <h1>Name: {EachDriver.CustomerName}</h1>
      <h1>Phone Number: {EachDriver.PhoneNumber}</h1>
      <h1>Email: {EachDriver.Email}</h1>
      <h1>Address: {EachDriver.Address}</h1>
      <h1>Country: {EachDriver.Country}</h1>
      <button onClick={(e) => DeleteDriver(e)} className='btn btn-primary'>
        Delete Driver
      </button>
    </>
  );
};

当我在我的子组件中单击 Delete Driver 时,它会从数据库中删除一个驱动程序,但由于 useEffect 的空依赖关系,页面在刷新之前不会重新呈现。

我想从子组件设置一个父状态并将其放入依赖数组中,但感觉像是一种反模式

1 个答案:

答案 0 :(得分:1)

从子组件更新父状态完全没问题。只需给子组件传递一个函数,当子组件改变状态时,在子组件内部调用这个函数,这样父组件就可以更新app状态和重新渲染。

这是一个示例 codesandbox

import React, { useState, useEffect } from "react";
import axios from "axios";

const Posts = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const getPosts = async () => {
      const response = await axios.get(
        `https://jsonplaceholder.typicode.com/posts`
      );

      setPosts(response.data);
    };
    getPosts();
  }, []);

  const handleDeletePost = (id) => {
    const updatedPosts = posts.filter((p) => p.id !== id);
    setPosts(updatedPosts);
  };

  return (
    <div>
      {posts.map((post) => (
        <PostInfo key={post.id} post={post} deletePost={handleDeletePost} />
      ))}
    </div>
  );
};

const PostInfo = ({ post, deletePost }) => {
  const DeletePost = async (id) => {
    await axios.delete(`https://jsonplaceholder.typicode.com/posts/{id}`);
    deletePost(id);
  };

  return (
    <>
      <h1>Id: {post.id}</h1>
      <h1>Title: {post.title}</h1>
      <button onClick={() => DeletePost(post.id)} className="btn btn-primary">
        Delete Post
      </button>
    </>
  );
};

export default Posts;