首页 > 解决方案 > Pattern for lookup values that support UIs (i.e. Country Codes, State Codes, etc) within React

问题描述

my reactjs application like most relies a bit on dropdowns that have pretty static data, things such as countries and states. In my application, the values are fetched from the server api.

I am wondering if there was a standard pattern for where to store those values for reuse across an application where that form input may reside on multiply UI's that are not connected.

Would a custom hook be appropriate here, or maybe a singleton service that holds the values that I can populate when the application is initializing?

标签: javascriptreactjs

解决方案


Option 1

You could store data in a javascript file assets/static/data.js

const data = {
  states: 'blah',
  countries: 'blah',
};
export default data;

Then in your client you can import it

import data from '../your/relative/path/assets/static/data.js';

Option 2

You could also create a .json file and use the json-loader package

Option 3

If you want to have multiple keys to import you can do the following...

export const states = ['Alabama', 'Alaska', ....];
export const countries = ['','', ....];

const data = {
    states ,
    countries,
};

export default data;

And you can now import the keys like so...

import {states} from '../your/relative/path/assets/static/data.js';

推荐阅读