简体   繁体   中英

How to set to true / false based on react props

const [effective_date_status, setEffectiveDateStatus] = React.useState(false)

I'm sending props value from parent to child. I want to set effective_date_status to false if props value is 0 & I want to set to true if props value is 1 .

Can anyone help me with this issue.

You can do as:

const [effective_date_status, setEffectiveDateStatus] = React.useState(
  !!props.value
);

or

const [effective_date_status, setEffectiveDateStatus] = React.useState(
  props.value === 0 ? false : true
);

or Lazy Initialisation

const [effective_date_status, setEffectiveDateStatus] = React.useState(() =>
  props.value === 0 ? false : true
);

first, import use effect hook and then try this

useEffect(()=>{
if(props.value === 1)
setEffectiveDateStatus(true);
else if(props.value === 0)
setEffectiveDateStatus(false);
},[props.value])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM