簡體   English   中英

如果在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM