You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ES6三元运算符写法及React mapStateToProps条件判断最佳实践

1. Using Ternary Operators for Conditional Statements in JavaScript ES6

The ternary operator is a concise alternative to basic if-else blocks, and in ES6 it plays nicely with modern features like arrow functions, destructuring, and template literals. Here's how to use it effectively:

Basic Syntax

The core structure stays consistent with standard JavaScript:

const result = condition ? expressionIfTrue : expressionIfFalse;

For example, checking if a number is even:

const num = 4;
const evenStatus = num % 2 === 0 ? "Even" : "Odd";
console.log(evenStatus); // Logs "Even"

ES6-Specific Use Cases

  • With Arrow Functions: Ideal for inline return logic:
    const getGreeting = (isMorning) => isMorning ? "Good morning!" : "Good evening!";
    
  • Nested Ternaries (use sparingly—over-nesting hurts readability):
    const score = 85;
    const grade = score >= 90 ? "A" : 
                  score >= 80 ? "B" : 
                  score >= 70 ? "C" : "D";
    
  • Combined with Destructuring:
    const user = { name: "Alice", age: 17 };
    const votingEligibility = user.age >= 18 ? "Eligible to vote" : "Not eligible";
    

2. Conditional Return Logic in React's mapStateToProps

Let's break down your scenario step by step. First, we need to return newObj only if state.manage.module includes "module1" or "module4Submodule"—and we also need to ensure those modules aren't null, undefined, or empty. Plus, we'll cover whether to write the condition directly in the return statement or handle it first.

First: Helper Function for Validation

Let's create a small reusable helper to check if a module is valid (non-null, non-undefined, and has properties):

const isValidModule = (module) => {
  return module !== null && module !== undefined && Object.keys(module).length > 0;
};

This keeps our main code clean and avoids repeating logic.

Option 1: Ternary in the Return Statement

This is concise for simple logic, but can get messy if conditions grow more complex:

const mapStateToProps = (state) => { 
  // Add default values to avoid destructuring errors if nested props are missing
  const { 
    module: { module1, module4: { submodule } = {} }, 
    manage: { module: manageModules } = {} 
  } = state; 
  
  const newObj = { module1, module4Submodule: submodule }; 
  
  // Check our core conditions
  const isModule1Valid = manageModules.includes('module1') && isValidModule(module1);
  const isModule4SubValid = manageModules.includes('module4Submodule') && isValidModule(submodule);
  
  return {
    testmodule: isModule1Valid || isModule4SubValid ? newObj : "somevalue"
  };
};

Option 2: Handle Conditions First, Then Return

This is my preferred approach for most cases, especially as logic expands. It's easier to read, debug, and extend:

const mapStateToProps = (state) => { 
  const { 
    module: { module1, module4: { submodule } = {} }, 
    manage: { module: manageModules } = {} 
  } = state; 
  
  const newObj = { module1, module4Submodule: submodule }; 
  
  const isModule1Valid = manageModules.includes('module1') && isValidModule(module1);
  const isModule4SubValid = manageModules.includes('module4Submodule') && isValidModule(submodule);
  
  let testmodule;
  if (isModule1Valid || isModule4SubValid) {
    testmodule = newObj;
  } else {
    testmodule = "somevalue";
  }
  
  return { testmodule };
};

Which Approach Is Better?

  • Use ternary in return for simple logic: If your condition is a single, straightforward check, the concise ternary works great.
  • Handle conditions first for complex logic: When you have multiple checks, need to add comments, or might extend the logic later, separating the condition from the return makes your code more maintainable. Other developers (and future you) will appreciate the clarity.

Also, note the default values added in the destructuring (= {})—this prevents errors if module4 or manage.module are missing from the state.


内容的提问来源于stack exchange,提问作者user13465472

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:02:43