reactjs - 如何使用钩子从子组件重新渲染父组件?
问题描述
当我单击子组件中的按钮时,我想强制我的父母重新呈现页面。(我不使用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>
);
}
为什么我的父页面不想重新渲染?提前致谢。
解决方案
我已经创建了您要实现的目标的概念证明,并且它有效:
https://codesandbox.io/s/weathered-smoke-ojr5j
可能您的代码中还有其他我们看不到的东西阻止了组件重新渲染
推荐阅读
- docker - 在 docker-compose 中运行容器时使用当前用户
- c++ - 为什么通过引用传递给函数的变量不会立即改变其值?
- graphics - 如何制作网状歧管
- r - as.POSIXct 没有解释日期 19/10/2008
- mysql - CPanel SQLSTATE[HY000] [1045] 拒绝用户访问
- selenium - 使用 selenium-webdriver 和 jest 检查元素的消失
- java - Java:如何从 Maven 故障安全插件访问元文件信息?
- python - 如何在python3中为请求库的post方法传递嵌套参数对象?
- angular - 使用 mat-table 显示嵌套数组
- python-3.x - 用于训练机器人的 Python 递归替代方案