ReactJS数组映射用变量:下拉切换生成多表的优化方案问询
Hey there! Great call trying to avoid repetitive code—this is exactly the kind of scenario where dynamic property access and reusable functions shine. Let me walk you through a clean, scalable solution:
Step 1: Map Dropdown Options to Your Property Suffixes
First, create a simple mapping object to link your dropdown's visible options to the suffixes used in your data properties. This keeps your logic organized and easy to update later (like if you add a "Quarterly" option down the line):
// Define the mapping between dropdown text and your property suffix const periodMapping = { 'Daily': 'day', 'Weekly': 'weekly', 'Monthly': 'monthly', 'Yearly': 'yearly' };
Step 2: Track the Selected Period
Set up a variable to store the current selected period, and add an event listener to your dropdown to update this variable when the user makes a selection:
// Get your dropdown element (adjust the selector to match your HTML) const periodDropdown = document.getElementById('period-select'); // Initialize with the dropdown's default selected value let currentPeriod = periodMapping[periodDropdown.value]; // Update the period when the dropdown changes periodDropdown.addEventListener('change', () => { currentPeriod = periodMapping[periodDropdown.value]; // Re-generate and render your table with the new period renderTable(); });
Step 3: Generate Table Data Dynamically
Replace your hardcoded map function with a dynamic version that uses template literals to access the correct properties based on currentPeriod. This way you only write the mapping logic once:
function generateTableData() { return records.map(record => { // Extract static properties const { id, sector_name } = record; // Dynamically fetch the period-specific lot properties return { id, sector_name, lot1: record[`f_${currentPeriod}_lot1`], lot2: record[`f_${currentPeriod}_lot2`], lot3: record[`f_${currentPeriod}_lot3`], lot4: record[`f_${currentPeriod}_lot4`] }; }); }
Step 4: Render Your Table
Wrap your table rendering logic in a reusable function that gets called on page load and whenever the dropdown changes:
function renderTable() { const tableData = generateTableData(); // Add your table rendering logic here (e.g., creating <tr> elements, populating cells) // Example placeholder: console.log(`Rendering ${currentPeriod} table data:`, tableData); // ... actual DOM manipulation code goes here } // Render the initial table when the page loads renderTable();
Why This Works
- No repetition: You only write the core mapping and rendering logic once, instead of four separate versions for each period.
- Easy to maintain: Adding a new period only requires updating the
periodMappingobject—no need to rewrite themapfunction or rendering code. - Cleaner code: Separating concerns (tracking selection, generating data, rendering) makes your code easier to read and debug.
If you prefer to keep the original property names (like f_day_lot1 instead of lot1), you can adjust the return object in generateTableData() to use dynamic keys:
return { id, sector_name, [`f_${currentPeriod}_lot1`]: record[`f_${currentPeriod}_lot1`], [`f_${currentPeriod}_lot2`]: record[`f_${currentPeriod}_lot2`], [`f_${currentPeriod}_lot3`]: record[`f_${currentPeriod}_lot3`], [`f_${currentPeriod}_lot4`]: record[`f_${currentPeriod}_lot4`] };
Just note that if you do this, your table rendering logic will need to dynamically reference these property names (instead of using static lot1, lot2, etc.).
内容的提问来源于stack exchange,提问作者user3643092

