简体   繁体   English

如何根据 props 在 React 中设置初始 useState 值

[英]How to set initial useState value in React based on props

I currently set my active state to 0:我目前将我的active state 设置为 0:

const [active, setActive] = useState(0);

but I'm wondering how I can set the initial value to null if one of my component props: isFilterMode is true?但我想知道如果我的组件道具之一: isFilterMode为真,如何将初始值设置为null So the initial state is "dynamic" based on the props?那么最初的 state 是基于道具的“动态”吗?

Try like this像这样试试

const [active, setActive] = useState(props.isFilterMode ? null : 0);

or using a callback function ( lazy initialization )或使用回调 function ( lazy initialization

const [active, setActive] = useState(() => props.isFilterMode ? null : 0);
const Component = ({ isFilterMode }) => {
  const [active, setActive] = useState(() => isFilterMode ? null : 0);
  ...
}

you can define an expression with a return value as an argument for useState.您可以定义一个带有返回值的表达式作为 useState 的参数。 With a ternary operator like props.isFilterMode? null: 0使用像props.isFilterMode? null: 0 props.isFilterMode? null: 0 you would return null if the value of props.isFilterMode evaluates to true and 0 otherwise. props.isFilterMode? null: 0如果props.isFilterMode的值为 true,则返回null ,否则返回 0。 So in useState you would have:因此,在useState中,您将拥有:

  const [active, setActive] = useState(props.isFilterMode ? null : 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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