[英]why role base parent of two child component have different state if update in one of these child component in reactjs
I want to know I have one parent component and two child components and these child components are separated according to the user role.我想知道我有一个父组件和两个子组件,这些子组件根据用户角色分开。 I have passed the parent state in these child components.
我已经在这些子组件中传递了父状态。 In the beginning, both child components have the same state value, but if I update the state value in one child component, it will not update the state value in another component why.
一开始,两个子组件具有相同的状态值,但是如果我更新一个子组件中的状态值,它不会更新另一个组件中的状态值,这是为什么。 Here is an example code.
这是一个示例代码。
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 component: Demo1 组件:
import React from "react";从“反应”导入反应;
const Demo1 = ({ staVal, setStaVal, handler }) => {
return (
<>
<div>demo1:{staVal}</div>
<button onClick={handler}>clik</button>
</>
);
};
export default Demo1;
Demo 2 component:演示 2 组件:
import React from "react";
const Demo2 = ({ staVal }) => {
return <div>demo2:{staVal}</div>;
};
export default Demo2;
Accessing localStorage
is a side effect .访问
localStorage
是一个副作用。
Side effects cannot be called from the render
method (for Class components) or the top level (function components).不能从
render
方法(对于 Class 组件)或顶层(函数组件)调用副作用。
In your code, access the localStorage inside useEffect(()=>{}, [])
or在您的代码中,访问
useEffect(()=>{}, [])
或
inside componentDidMount
if you want to make it a class component.如果您想让它成为类组件,请在
componentDidMount
内。
use the useEffect to get the item from the local storage.
使用 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.