Methods to reference json in react: 1. Import directly and use [create-react-app] to build the project; 2. Change the json file to a js file and assign the data in the original json to variables data.
This method is suitable for all brands of computers
react Methods of quoting json in:
The first way: directly import
You need to use the json-loader
module, if you are Use create-react-app
to build the project, then the module is already included.
You only need to use import to introduce the json file like a component, import data from '. ./lessonlist/courselist.json';
data is the name I chose myself, similar to the component name. There is no need to export default data to export, but writing this in the json file will also report an error
Second: Change the json file into a js file
Change the json file into a js file, and then assign the data in the original json to the variable data,
Just use import to introduce it, import data from '../lessonlist/courselist.js';
These two methods to access data are as follows
<span className="lesson-link-line1">{data[0].name}</span> <span className="lesson-link-line1">{data[0].url}</span> <span className="lesson-link-line1">{data[1].name}</span> <span className="lesson-link-line1">{data[1].url}</span> <span className="lesson-link-line1">{data[2].name}</span> <span className="lesson-link-line1">{data[2].url}</span>
The main difference between these two methods
json files do not need to be exported by default, and this syntax is not supported, and an error will be reported.
js file needs to assign data to a variable. In the export default export,
The attributes and values in the json file must be double Quotes, otherwise an error will be reported. js file attributes do not need to be double quotes
Related free learning recommendations: javascript (video)
The above is the detailed content of How to reference json in react. For more information, please follow other related articles on the PHP Chinese website!