[英]How to update a parent's component state from a child component in Reactjs
[英]why role base parent of two child component have different state if update in one of these child component in reactjs
我想知道我有一个父组件和两个子组件,这些子组件根据用户角色分开。 我已经在这些子组件中传递了父状态。 一开始,两个子组件具有相同的状态值,但是如果我更新一个子组件中的状态值,它不会更新另一个组件中的状态值,这是为什么。 这是一个示例代码。
import React, { useEffect, useState } from "react";
import Demo1 from "./Demo1";
import Demo2 from "./Demo2";
const Demo = () => {
const [staVal, setStaVal] = useState("hi");
console.log(staVal);
const user = JSON.parse(localStorage.getItem("auth"));
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
export default Demo;
Demo1 组件:
从“反应”导入反应;
const Demo1 = ({ staVal, setStaVal, handler }) => {
return (
<>
<div>demo1:{staVal}</div>
<button onClick={handler}>clik</button>
</>
);
};
export default Demo1;
演示 2 组件:
import React from "react";
const Demo2 = ({ staVal }) => {
return <div>demo2:{staVal}</div>;
};
export default Demo2;
访问localStorage
是一个副作用。
不能从render
方法(对于 Class 组件)或顶层(函数组件)调用副作用。
在您的代码中,访问useEffect(()=>{}, [])
或
如果您想让它成为类组件,请在componentDidMount
内。
使用 useEffect 从本地存储中获取项目。
const [user,setUser]=useState(null);
useEffect(()=>{
const currentUser = JSON.parse(localStorage.getItem("auth"));
setUser(currentUser)
},[])
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
); };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.