如何从不是父母或孩子的另一个组件更改功能组件的状态?

问题描述 投票:0回答:1

在我的代码中,我有一个功能组件,该组件使用“更多加载”分页呈现数据库中的用户列表,而当您单击某些操作时,该组件将显示用户详细信息以及一些操作,类似于文件浏览器。这些操作之一是删除用户。这样做时,用户列表不会更新,并且如果您单击刚删除的用户,则会出现执行错误,因为代码尝试使用空对象中的信息。在删除用户而不使用类组件的情况下更新列表组件的最佳方法是什么?

App.js-列表和详细信息组件的父级

<BrowserRouter>
  <div id = "app">
    <div className = "section sectionTop">
      <Route path = "/" component = {BaseTop}/>
    </div>
    <div className = "Main">
      <div className = "section sectionMain sectionLeft">
      <Route path = "/" component = {BaseLeft}/>
      </div>
      <div className = "section sectionMain sectionCenter">
        <Route path = "/" exact component = {BaseCenter}/>
        <Route path = "/listusers" component = {UserList}/>
      </div>
      <div className = "section sectionMain sectionRight">
        <Route path = "/" exact component = {BaseRight}/>
        <Route path = "/adduser" component = {UserAdd}/>
        <Route path = "/listusers/:id" component = {UserInfo}/>
      </div>
    </div>
  </div>
</BrowserRouter>

UserList.js-用户列表

const [users, setUsers] = useState ([]);
const [page, setPage] = useState (0);

useEffect
(
    () =>
    {
        setPage (page+1);
    },
    []
);

useEffect
(
    () =>
    {
        try
        {
            const runEffect = async () =>
            {
                const response = await api.get
                (
                    `/users?page=${page}`
                );
                setUsers ([...users, ...response.data.docs]);
            }
            runEffect();
        }
        catch (error)
        {
            console.log (error);
        }
    },
    [page]
);

return (
    <div className = "userListArea">
        {
            users.map
            (
                (user, index) =>
                {
                    return (
                        <div key = {index} className = "user">
                            <Link key = {index} to = {`/listusers/${user._id}`}>
                                <button
                                className = "buttonUser"
                                key = {index}>
                                    {user.name}
                                </button>
                            </Link>
                        </div>
                    )
                }
            )
        }
        <button
        className = "buttonLoadMore"
        onClick = {() => setPage (page+1)}>
            Carregar mais
        </button>
    </div>
)

UserInfo.js-用户的详细信息

const [user, setUser] = useState ({});
const [_id, set_id] = useState ("");

useEffect
(
    () =>
    {
        if (user.hasOwnProperty ("_id") === false)
        {
            set_id (match.params.id);
        }
        else
        {
            if (user._id !== match.params.id)
            {
                set_id (match.params.id);
            }
        }
        const runEffect = async () =>
        {
            const response = await api.get
            (
                "/searchuser",
                {
                    params:
                    {
                        _id
                    }
                }
            )
            if (user.hasOwnProperty ("name") === false)
            {
                setUser (response.data);
            }
            else
            {
                if (user.name !== response.data.name)
                {
                    setUser (response.data);
                }
            }
        }
        runEffect();
    }
);

async function handleDeleteUser (_id)
{
    if (window.confirm(`Você realmente deseja remover o usuário ${user.name}?`))
    {
        const response = await api.delete
        (
            "/users",
            {
                params:
                    {
                        _id
                    }
            }
        );
        if (response.data._id === _id)
        {
            window.alert(`O usuário ${user.name} foi excluído.`);
        }
    }
}

return (
    <div className = "userInfoArea">
        <div className = "name">{user.name}</div>
        <div className = "email">{user.email}</div>
        <button className = "buttonEdit">Editar</button>
        <Link to = "/listusers">
            <button
            className = "buttonDelete"
            onClick = {() => handleDeleteUser (user._id)}
            >
                Excluir
            </button>
        </Link>
    </div>
)
javascript reactjs react-router components react-hooks
1个回答
0
投票
如果不使用外部状态管理解决方案,例如Redux或新的useContext api / hook,则无法更新不是父级或子级的组件的状态。这些库涉及将所有单个组件的状态移动到更大的集中式全局状态,该状态可以被所有组件更新和访问。
© www.soinside.com 2019 - 2024. All rights reserved.