ReactJS中如何避免重复编写相同函数?——postDate函数复用方案咨询
postDate Function Across Multiple Pages Great question—duplicating code is a surefire way to create maintenance headaches later on. Let’s walk through the cleanest, most scalable ways to fix this:
Option 1: Use ES Modules (Modern Frontend/Node.js)
This is the standard approach for most modern JavaScript projects (React, Vue, vanilla JS with module support).
Step 1: Create a Utility File
Make a dedicated file to hold your reusable functions—something like dateUtils.js (you can name it whatever makes sense for your project):
// dateUtils.js export const postDate = (fullDate) => { // Pro tip: Optimize the function to split only once (better performance!) const dateParts = fullDate.split(" "); return `${dateParts[1]} ${dateParts[2]}, ${dateParts[3]}`; };
Step 2: Import the Function in Your Pages
In every page where you need to use postDate, import it from your utility file:
// Example: page1.js, page2.js, or page3.js import { postDate } from './dateUtils.js'; // Use it just like before! const myFormattedDate = postDate('Thu Feb 15 2024 09:30:00'); console.log(myFormattedDate); // Output: "Feb 15, 2024"
Note: Adjust the import path (./dateUtils.js) to match where your utility file lives relative to the current page. For example, if it’s in a utils folder, use ./utils/dateUtils.js.
Option 2: Use CommonJS (Older Node.js Projects)
If you’re working in an environment that uses CommonJS (like older Node.js apps or Webpack setups without ES module support), use this approach instead:
Step 1: Export the Function
// dateUtils.js const postDate = (fullDate) => { const dateParts = fullDate.split(" "); return `${dateParts[1]} ${dateParts[2]}, ${dateParts[3]}`; }; module.exports = { postDate };
Step 2: Require the Function in Your Pages
// Example: page1.js, page2.js, or page3.js const { postDate } = require('./dateUtils.js'); // Same usage as before const formattedDate = postDate('Wed Mar 20 2024 14:00:00');
Bonus: A Quick Optimization
Your original function uses split() twice, which is unnecessary. By splitting the date string once into an array and accessing the indexes directly (like I did above), you get the same result with better performance—win-win!
Why This Works
- Single Source of Truth: You only write and maintain the
postDatefunction once. If you need to fix a bug or tweak the formatting, you update it in one place instead of three. - Cleaner Code: No more cluttering your page files with duplicate function definitions.
- Scalability: You can add more date-related functions to
dateUtils.jslater (like formatting for time zones, relative dates, etc.) without repeating yourself.
内容的提问来源于stack exchange,提问作者sang10

