簡體   English   中英

如何使用 React.useState() 中的條件更改屬性

[英]How to change property with a condition inside React.useState()

我有一個組件,它使用React.useState來保持一個名為available的屬性,我想做的是使用條件語句將其值更改為 true,以便我的組件根據該條件呈現,但我無法設置在React.useState中添加一個條件語句。 我嘗試使用條件語句在我的其他組件中更改它:

  const [isUserLogged] = React.useState(true);
  const arrowDir = props['data-expanded']
    ? 'k-i-arrow-chevron-down'
    : 'k-i-arrow-chevron-right';

  if (isUserLogged === true) {
    props.available === true;
  }

但這也沒有用。 如何使用條件語句來實現這一點? 這是我的整個代碼:

import * as React from 'react';
import { withRouter } from 'react-router-dom';
import {
  Drawer,
  DrawerContent,
  DrawerItem,
} from '@progress/kendo-react-layout';
import { Button } from '@progress/kendo-react-buttons';

const CustomItem = (props) => {
  const { visible, ...others } = props;
  const [isUserLogged] = React.useState(true);
  const arrowDir = props['data-expanded']
    ? 'k-i-arrow-chevron-down'
    : 'k-i-arrow-chevron-right';

  if (isUserLogged === true) {
    props.available === true;
  }

  return (
    <React.Fragment>
      {props.available === false ? null : (
        <DrawerItem {...others}>
          <span className={'k-icon ' + props.icon} />
          <span className={'k-item-text'}>{props.text}</span>
          {props['data-expanded'] !== undefined && (
            <span
              className={'k-icon ' + arrowDir}
              style={{
                position: 'absolute',
                right: 10,
              }}
            />
          )}
        </DrawerItem>
      )}
    </React.Fragment>
  );
};

const DrawerContainer = (props) => {
  const [drawerExpanded, setDrawerExpanded] = React.useState(true);
  const [isUserLogged] = React.useState(true);

  const [items, setItems] = React.useState([
    {
      text: 'Education',
      icon: 'k-i-pencil',
      id: 1,
      selected: true,
      route: '/',
    },
    {
      separator: true,
    },
    {
      text: 'Food',
      icon: 'k-i-heart',
      id: 2,
      ['data-expanded']: true,
      route: '/food',
    },
    {
      text: 'Japanese Food',
      icon: 'k-i-minus',
      id: 4,
      parentId: 2,
      route: '/food/japanese',
    },
    {
      text: 'Secret Food',
      icon: 'k-i-minus',
      id: 5,
      parentId: 2,
      route: '/food/italian',
      available: false,
    },
    {
      separator: true,
    },
    {
      text: 'Travel',
      icon: 'k-i-globe-outline',
      ['data-expanded']: true,
      id: 3,
      route: '/travel',
    },
    {
      text: 'Europe',
      icon: 'k-i-minus',
      id: 6,
      parentId: 3,
      route: '/travel/europe',
    },
    {
      text: 'North America',
      icon: 'k-i-minus',
      id: 7,
      parentId: 3,
      route: '/travel/america',
    },
  ]);

  const handleClick = () => {
    setDrawerExpanded(!drawerExpanded);
  };

  const onSelect = (ev) => {
    const currentItem = ev.itemTarget.props;
    const isParent = currentItem['data-expanded'] !== undefined;
    const nextExpanded = !currentItem['data-expanded'];
    const newData = items.map((item) => {
      const {
        selected,
        ['data-expanded']: currentExpanded,
        id,
        ...others
      } = item;
      const isCurrentItem = currentItem.id === id;
      return {
        selected: isCurrentItem,
        ['data-expanded']:
          isCurrentItem && isParent ? nextExpanded : currentExpanded,
        id,
        ...others,
      };
    });
    props.history.push(ev.itemTarget.props.route);
    setItems(newData);
  };

  const data = items.map((item) => {
    const { parentId, ...others } = item;

    if (parentId !== undefined) {
      const parent = items.find((parent) => parent.id === parentId);
      return { ...others, visible: parent['data-expanded'] };
    }

    return item;
  });
  return (
    <div>
      <div className="custom-toolbar">
        <Button icon="menu" look="flat" onClick={handleClick} />
        <span className="title">Categories</span>
      </div>
      <Drawer
        expanded={drawerExpanded}
        mode="push"
        width={180}
        items={data}
        item={CustomItem}
        onSelect={onSelect}
      >
        <DrawerContent>{props.children}</DrawerContent>
      </Drawer>
    </div>
  );
};

export default withRouter(DrawerContainer);

如果在渲染組件時存在props.available ,則可以編寫條件表達式,同時在 useState 中聲明isLoggedIn

如果它稍后可用,我們總是可以使用useEffect掛鈎來更新isLoggedIn

const Component = (props) => {
// if props.available is already present to you
const [isLoggedIn, setIsLoggedIn] = React.useState(props.isAvailable ? true : false);

// if props.isAvailable is not present when your component renders you can use
// useEffect

React.useEffect(() => {
  setIsLoggedIn(props.isAvailable);
}, [props.isAvailable])

 // use IsLoggedIN here
return (
  <div>
  {
    isLoggedIn ? 
      <div> Logged in </div> 
     : <div>llogged out</div>
   }
  </div>            

)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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