admin管理员组

文章数量:1353897

I have a simple functional ponent and would like to initialize the state with a boolean, depending on the condition. For example:

export default() => {

  const st = useSelector(state => state.body);
  const { type } = st;

  let bool = type === 'test'

  const [ hidden, setHidden ] = useState(bool) //this is always true

}

st is just fetching the state from redux, type will be condition. In some cases type will be test so bool will be true, but when it's initializing the state it's always false.

I do a console.log after the useState and hidden displays false???

I'm not sure what's causing to be false. Am i missing something? I appreciate your help and insights

I have a simple functional ponent and would like to initialize the state with a boolean, depending on the condition. For example:

export default() => {

  const st = useSelector(state => state.body);
  const { type } = st;

  let bool = type === 'test'

  const [ hidden, setHidden ] = useState(bool) //this is always true

}

st is just fetching the state from redux, type will be condition. In some cases type will be test so bool will be true, but when it's initializing the state it's always false.

I do a console.log after the useState and hidden displays false???

I'm not sure what's causing to be false. Am i missing something? I appreciate your help and insights

Share Improve this question edited Mar 3, 2020 at 15:26 ssten 2,0591 gold badge19 silver badges30 bronze badges asked Mar 3, 2020 at 15:14 medev21medev21 3,05110 gold badges35 silver badges51 bronze badges 1
  • bool will be set to false unless type === 'test', without knowing what type is, this is expected. – amcquaid Commented Mar 3, 2020 at 15:18
Add a ment  | 

1 Answer 1

Reset to default 7

As you said

st is just fetching the state from redux

This is probably the problem.

Probably in the first render, what you get from the redux isn't the correct value (probably null or undefined), so it sets the default value of the state as false, and then happens a second render where it returns the correct value, but won't reassign it to the state.

The default value of useState will be set only in the first render, and if in the first render it isn't what you want, it won't change, unless you set it.

What you could do is use useEffect hook to reset hidden when type changes

export default () => {

  const st = useSelector(state => state.body);
  const { type } = st;

  let bool = type === 'test';

  const [ hidden, setHidden ] = useState(bool) //this is always true

  // reset hidden if type changes
  useEffect(() => {
      setHidden(type === 'test')
  }, [type])

}

本文标签: javascriptwhy boolean variable is passed to useState() is always false React hooksStack Overflow