简体   繁体   English

如何使用 React.useState() 中的条件更改属性

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

I have a component that uses React.useState to keep a property named available and what I want to do is to change its value to true with a conditional statement, so that my component gets rendered based on that condition, but I can't set up a conditional statement inside React.useState .我有一个组件,它使用React.useState来保持一个名为available的属性,我想做的是使用条件语句将其值更改为 true,以便我的组件根据该条件呈现,但我无法设置在React.useState中添加一个条件语句。 I tried changing it in my other component with a conditional statement:我尝试使用条件语句在我的其他组件中更改它:

  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;
  }

But that didn't work too.但这也没有用。 How can I achieve this with a conditional statement?如何使用条件语句来实现这一点? Here is my entire code:这是我的整个代码:

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);

if props.available is present when your component is rendering you can write a conditional expression while declaring the isLoggedIn inside useState.如果在渲染组件时存在props.available ,则可以编写条件表达式,同时在 useState 中声明isLoggedIn

In case it is available later we can always use useEffect hook to update the 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