javascript React UseState未立即更新

shyt4zoc  于 2022-12-28  发布在  Java
关注(0)|答案(1)|浏览(175)

我正在尝试构建一个react登录页面,显示基于props.products的不同屏幕。如果产品存在于API调用响应中,它将更新产品的全局状态,并将产品从null更新为数组。我在这里面临的问题是,即使状态更新(我已经检查过Redux开发工具),页面没有显示正确的屏幕。当试图加载屏幕类型3时出现问题。

function LandingPage(props) {
  const [eligibleProducts, setEligibleProducts] = useState([]);
  const [screenType, setScreenType] = useState();
  const [url, setUrl] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [isActive, setisActive] = useState(false);

  const { pocBusinessEmail, pocBusinessName } = props;

  useEffect(() => {
    handleEligibleProducts();
  }, []);

  useEffect(() => {
    console.log('count')
    if(props.products && (props.products.filter((product) => product.productStatus === 2).length > 0)){
      console.log("init")
      setisActive(true)
    }
  }, [props.products]);

  useEffect(() => {}, [props.eligibleProducts]);
  

  const handleEligibleProducts = async () => {
    setLoading(true);
    let data = {
      userType: 102,
    };
    data["email"] = window.localStorage.getItem("email");

    try {
      
      const res = await props.getEligibleProducts(data);
      const { statusCode, msgText, productList, Url } = res.data.responsePayload;
      let allEligibilityFlagZero = false;
      let noidforsome = false;
      if (Url.length != "") {
        setUrl(new URL(Url));
      }
     if(statusCode === 200){
          let data = {};
          data["employeeId"] = props.employeeId;
          data["products"] = null;
          await props.employeeProduct(data);
      } 

      if (productList) {
        setEligibleProducts(productList.map((product) => ({ ...product, selected: false })));
        allEligibilityFlagZero = productList.length && productList.every((product) => product.eligibilityFlag === 0);
       // noArcIdForSomeProduct = productList.length && productList.some((product) => !(product && (product.arcId || product.arcId !== null)));
      //  if(props.products){
      //     if((props.products.filter((product) => product.productStatus === 2).length > 0)){
      //       setisActive(true)
      //     }
      //   }
      

      
        }

      if (statusCode !== 200) {
        setScreenType(4);
        setMessage(msgText);
      } else if (!(productList && productList.length !== 0) || allEligibilityFlagZero) {
        setScreenType(1);
      } else if (!isActive) {
        setScreenType(2);
      } else {
        setScreenType(3);
      }
      setLoading(false);
      
    } catch (error) {
      setLoading(false);
      console.log("big error: " + error);
    }
  };
  let navigate = useNavigate();
  const routeChange = (direction) => {
    let path = direction;
    navigate(path);
  };

  const getProperScreen = () => {
    switch (screenType) {
      case 1:
        return <ScreenOne eligibleProducts={eligibleProducts} />;

      case 2:
        return <ScreenTwo eligibleProducts={eligibleProducts} handleSelectProduct={handleSelectProduct} selectUnSelectAllProduct={selectUnSelectAllProduct} />;

      case 3:
        return <ScreenThree eligibleProducts={eligibleProducts} handleSelectProduct={handleSelectProduct} selectUnSelectAllProduct={selectUnSelectAllProduct} products= {props.products} />;

      case 4:
        return <ErrorScreen message={message} />;
      
      default: 
        return <ScreenOne eligibleProducts={eligibleProducts} />;
    }
  };

  if (loading) return <Loader />;

  return (
    <>
      <Container maxWidth={false}>
        <Grid container sx={{ justifyContent: "space-between", p: "1rem 2rem" }}>
          <Grid item>
            <Box>
              <Header registrationBool={true} loggedInBool={true} pocBusinessEmail={pocBusinessEmail} pocBusinessName={pocBusinessName} />
            </Box>
          </Grid>
        </Grid>
      </Container>
      {getProperScreen()}
      {<FooterButtonContainer title="Apply Now" handleApplyNow={handleApplyNow} eligibleProducts={eligibleProducts} />}
      <Footer />
    </>
  );
}

export default LandingPage;
zdwk9cvp

zdwk9cvp1#

我看到的唯一问题是handleEligibleProducts依赖于isActiveprops,但是调用它的效果钩子没有依赖性。
最好不要在效果挂钩中调用组件中定义的函数,因为依赖关系图会变得混乱。相反,在效果挂钩本身中定义函数,并确保列出所有依赖关系。

const { products, getEligibleProducts, employeeId, employeeProduct } = props;

useEffect(() => {
  const handleEligibleProducts = async () => {
    // ...
  };

  handleEligibleProducts();
}, [
  isActive,
  getEligibleProducts,
  products,
  getEligibleProducts,
  employeeId,
  employeeProduct,
]);

正如F.Müller所提到的,您最好使用能够指出这些问题的linter。

相关问题