简体   繁体   中英

how to avoid undefined data when getting data from redux using useSelector?

Please let me know how to get data conditionally (if exists) when working with useSelector in reactJs component. Sometimes the required data is not available untill a certain component renders first.

You can use the optional chaining operator ?. to safely access a property on an object that might not exist. You can combine this with the logical OR operator ||to set a default value if the user or user_name is not set.

const user_name = useSelector(state => state.user?.user_name) || ''

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