最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React structure for own utils files - Stack Overflow

programmeradmin1浏览0评论

Is there any best practice in structure React app? Sometimes, I need to move universal functions to separate files. But, where? It's not a node_module.

src/
├─ actions/
├─ components/
├─ reducers/
├─ utils/           ← This is my utils folder.
│  ├─ DateUtils.js
│  ├─ NumberUtils.js
│  ├─ StringUtils.js
├─ views/
.git
.gitignore
node_modules/
package.json

The another way is creating Base react component that will contain all utils. All another react files will be child of this component.

class MyBaseComponent extends React.Component {

    dateUtilsMethod() {
       ...
    }

    stringUtilsMethod(myString) {
        ...
    }

}

class MainPageView extends MyBaseComponent { ... }

What is the best solution?

Is there any best practice in structure React app? Sometimes, I need to move universal functions to separate files. But, where? It's not a node_module.

src/
├─ actions/
├─ components/
├─ reducers/
├─ utils/           ← This is my utils folder.
│  ├─ DateUtils.js
│  ├─ NumberUtils.js
│  ├─ StringUtils.js
├─ views/
.git
.gitignore
node_modules/
package.json

The another way is creating Base react component that will contain all utils. All another react files will be child of this component.

class MyBaseComponent extends React.Component {

    dateUtilsMethod() {
       ...
    }

    stringUtilsMethod(myString) {
        ...
    }

}

class MainPageView extends MyBaseComponent { ... }

What is the best solution?

Share Improve this question edited Feb 12, 2023 at 21:13 Henry Ecker 35.6k19 gold badges45 silver badges64 bronze badges asked Sep 12, 2017 at 10:00 VesmyVesmy 1,2784 gold badges17 silver badges29 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

I think that you are on the right track, though it is arguable.
One thing that is missing in my opinion is an index file in the utils folder that exposes each util file via export.
for example:

//utils/index.js:  

 export { default as DateUtils} from './DateUtils';
 export { default as StringUtils} from './StringUtils';
 export { default as NumberUtils} from './NumberUtils';

And you will import them from other files like so:

import { DateUtils, NumberUtils} from '../utils ';

Or import all as alias:

import * as utils from '../utils ';
发布评论

评论列表(0)

  1. 暂无评论