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 unlesstype === 'test'
, without knowing whattype
is, this is expected. – amcquaid Commented Mar 3, 2020 at 15:18
1 Answer
Reset to default 7As 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
版权声明:本文标题:javascript - why boolean variable is passed to useState() is always false? React hooks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743914778a2561029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论