今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

React.js ~The best practice for conditional statement~

Ogasawara Kakeru 2026年06月26日 08:27 2 次阅读 来源:Dev.to

We tend to write React as functional programming because the functional component is the mainstream. In this era, one of the issues we often encounter is conditional statements. There are a variety of conditional statements, such as if, switch, and ternary operator. We confuse when to use them properly. Assign the result of the conditional statement into a variable This makes it easy to read, test, and modify codebases. The representative case is ternary operator const userName = user ? user . name : ' No user found ' ; Of course, we can write the code another way. const point = 80 ; let result ; if ( point >= 70 ) { result = ' passed ' ; } else { result = ' failed ' ; } console . log ( result ); // passed In this way, we can not ensure the immutability of let , and this section with the conditional branch is written in a procedural style. To solve this issue, we have to wrap this in a function. const judge = ( point : number ) => { if ( point >= 70 ) { return ' passed ' ; } return ' failed ' ; }; In addition to wrapping that statement, I suggest that you use early return to save the else statement. Do not write conditional statements in the return value of tsx (the UI rendering portion) ** When there is only a single conditional statement, or there is no need for any execution in the conditional statement. Let's use the ternary operation simply. import { FC } from ' react ' ; import { useQuery } from ' @tanstack/react-query ' ; import getUser from ' domains/getUser ' ; type Props = { userId : number ; }; const Profile : FC < Props > = ( props ) => { const { userId } = props ; const getSpecificUser = async () => { const specificUser = await getUser ( userId ); return specificUser ; }; const { data : user } = useQuery ([ ' user ' , userId ], getSpecificUser ); const userName = user ? user . name : ' User not found ' ; return < p > User : { userName } < /p> ; }; export default Profile ; const userName = user ? user . name : ' User not found ' ; In this statement, you

本文内容来源于互联网,版权归原作者所有
查看原文