最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set initial useState value in React based on props - Stack Overflow

programmeradmin2浏览0评论

I currently set my active state to 0:

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

but I'm wondering how I can set the initial value to null if one of my ponent props: isFilterMode is true? So the initial state is "dynamic" based on the props?

I currently set my active state to 0:

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

but I'm wondering how I can set the initial value to null if one of my ponent props: isFilterMode is true? So the initial state is "dynamic" based on the props?

Share Improve this question asked Nov 18, 2021 at 10:35 ctscts 1,0842 gold badges14 silver badges41 bronze badges 1
  • 2 useState(props.isFilterMode ? null : 0) – Keith Commented Nov 18, 2021 at 10:37
Add a ment  | 

3 Answers 3

Reset to default 5

Try like below

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

Or

using a callback function (lazy initialisation)

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. With a ternary operator like props.isFilterMode ? null : 0 you would return null if the value of props.isFilterMode evaluates to true and 0 otherwise. So in useState you would have:

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

And like Amila suggested in the other answer you can use a callback as a parameter to useState and whatever is evaluated and returned from that callback would be your initial state using arrow functions you would do something like:

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

or more explicitly but with longer code:

  const [active, setActive] = useState(() => { if(props.isFilterMode){ return null;} else { return 0;} } );
发布评论

评论列表(0)

  1. 暂无评论