首页 > 解决方案 > 如何使用钩子从子组件重新渲染父组件?

问题描述

当我单击子组件中的按钮时,我想强制我的父母重新呈现页面。(我不使用redux,因为我的项目中没有时间学习,所以我使用localStorage。不幸的是React看不到什么时候对本地Storage进行了更改,所以他没有重新渲染. 这就是为什么我想强制它重新渲染我的页面(以获得正确的内容)。)

我尝试使用带有函数 useState 的钩子来执行此操作,但它不起作用,我不知道为什么......(我的页面没有任何变化)

这是我的父页面:(只是代码很重要)

const[reload, setReload] = useState(false);
...
else if (user) { contents = [<Message_UserIdentified user={user} callBack={setReload}/>, contentform]; }

这是我的子组件:

const Message_UserIdentified = (props) => {
    let user = props.user;
    return (
        <Alert color="primary" className="alert alert-dismissible alert-info">
            <h4>Welcome {!user ? "" : user.firstname} {!user ? "" : user.lastname}</h4>
            If you are not {!user  ? "" : user.firstname} click <a onClick={() => {localStorage.removeItem('idUser'); props.callBack(true);}}>here.</a>
        </Alert>
    );
}

为什么我的父页面不想重新渲染?提前致谢。

标签: reactjs

解决方案


我已经创建了您要实现的目标的概念证明,并且它有效:

https://codesandbox.io/s/weathered-smoke-ojr5j

可能您的代码中还有其他我们看不到的东西阻止了组件重新渲染


推荐阅读