Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use mockjs method in react

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to use the mockjs method in react". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the mockjs method in react.

Introduction

Mock means "imitate" or "simulate". To put it simply, it means to create data, almost any data you want, including api and data returned through api.

You can use mockjs to return random data when you are self-testing after writing a project, or if you need data to write a page but do not want to open a separate backend.

Install & uninstall & introduce / / install npm I mockjs// Uninstall npm uninstall mockjs// Project introduce import Mock from 'mockjs' basic syntax & specification

Mock.mock

To create data, you need to use the mock method:

Mock.mock (xxx) / / the xxx in this is the data to be simulated through mock

Each falsified data consists of three parts:

Attribute name name

Generate rule rule

Attribute value value

For example:

Const data = Mock.mock ({code: '0percent, msg:' success', 'list | 5percent: [{name:' @ name', age:'@ integer (18,25)'}]})

Code, msg and list here are all attribute names, where list and msg are strings and list is an array

The data for code and msg are too simple, so the generation rules are omitted here

The corresponding generation rule of list is | 5, which means to generate an array containing five elements.

Here,'0', 'success', and [{name:' @ name', age:'@ integer (18,25)'}] are their respective values.

Print the generated results to see:

Console.log (data) / * results are as follows * / {"code": "0", "msg": "success", "list": [{"name": "Nancy Lewis", "age": 18}, {"name": "Gary Wilson" "age": 25, {"name": "Shirley Gonzalez", "age": 22}, {"name": "Mark Moore", "age": 24}, {"name": "Richard Gonzalez" "age": 22}]} / / in addition As can be seen from multiple prints, the results are different each time, and the data are random.

As can be seen from the above example, the generation rules are optional and not necessary

If a generation rule exists, then the attribute name and the generation rule need to be separated by |

7 kinds of generation rules

'name | min-max': value

/ / indicates the number of times the value value is repeated, at least min times The maximum number of max times const data = Mock.mock ({'list | 1-5 cycles: [' hello-']}) / / the result may be: ["hello-", "hello-"] / / it may also be: ["hello-", "hello-", "hello-"] / / hello- is randomly repeated 1-5 times as a result

'name | count': value

/ / value regularly repeats count times const data = Mock.mock ({'list | 2 seconds: [' hello-']}) / / the result is: ["hello-", "hello-"]

'name | min-max.dmin-dmax': value

/ / when value is numeric, a floating point number is generated. / / the integer part of the floating point number is greater than or equal to min, less than or equal to max, and the decimal part retains dmin to dmax bits. / / the generated value is independent of the value value originally written. The initial value of value is only used to determine the data type const data = Mock.mock ({'num1 | 1-100.1-3 values: 1}).

The resulting result may be:

It could also be:

'name | min-max.dcount': value

/ / when value is numeric, a floating point number is generated. / / the integer part of the floating point number is greater than or equal to min, less than or equal to max, and the decimal part retains the dcount bit. / / the generated value is independent of the value value originally written. The initial value of value is only used to determine the data type.

'name | count.dmin-dmax': value

/ / when value is numeric, a floating point number is generated. / / the integer part of the floating point number is equal to count, and the decimal part retains the dmin to dmax bits. / / the generated value is independent of the value value originally written. The initial value of value is only used to determine the data type.

'name | count.dcount': value

/ / when value is numeric, a floating point number is generated. / / the integer part of the floating point number is count, and the decimal part retains the dcount bit. / / the generated value is independent of the value value originally written. The initial value of value is only used to determine the data type.

'name | + step': value

/ / when value is a number, the initial value is value, and each result will be incremented by 1 to generate the relationship between the rule and the attribute value value

Property value is a Boolean value

'name | 1 value: value// when value is true or false / / the final result will return a Boolean, the probability of returning true is 1, 2, and the probability of returning false is also 1/2'name | min-max': value// when value is a result representing a Boolean value, / / a Boolean value is randomly generated, the probability of value is min / (min + max), / / the probability of value is max / (min + max)

The property value is the object Object

'name | count attributes randomly selected from count': object// slave value object' name | min to max attributes are randomly selected from min-max': object// slave value object

The attribute value is the array Array

'name | 1 attribute: array// one element is randomly selected from the attribute value array as the final value.' Name | + 1 attribute: array//, one element is selected sequentially from the attribute value array as the final value. Name | min-max': array// generates a new array by repeating the attribute value array, with the number of repeats greater than or equal to min and less than or equal to max. / / 'name | count': array generates a new array by repeating the attribute value array, and the number of repeats is count.

The property value is the regular expression RegExp

/ / reverse generates a string that matches it based on the regular expression regexp. The string Mock.mock ({'regexp1': / [Amurz] [Amurz] [0-9] /,' regexp2': /\ w\ W\ s\ S\ d\ D, 'regexp3': /\ d {5pr 10} /}) / / the result may be: {"regexp1": "pJ7", "regexp2": "F)\ fp1G", "regexp3": "561659409"} placeholder @

Placeholders refer to methods in Mock.Random

This is very similar to the v-on:click omitted @ click in vue. It can be simply understood as the abbreviation of Mock.Random.

@ is followed by some fixed methods of Mock.Random to generate random data.

Usage example:

/ / for example, we are going to randomly generate a Chinese name const data = Mock.Random.cname () / / result: / / data: Zhao Li

The way to change to a placeholder is:

Const data = Mock.mock ('@ cname') / / result: / / data: Zhang Xiulan

Cname here is a method of Mock.Random, which means to get random Chinese names.

Here is a table containing Mock.Random 's methods and a simple classification:

The method name preceded by c is used to obtain Chinese-related data. For example, @ name is used to generate random English names, while @ cname is used to generate random Chinese names.

In addition, these methods can take parameters, and here are some examples:

Import Mock from 'mockjs'let basicData = Mock.mock ({' list | 1-100 seconds: [{'id | + 1 percent: 1, 'isBoolean':' @ boolean (10, 0, true)', / / 100% true 'naturalNumber':' @ natural (1, 0)', / / integers greater than or equal to zero 'integer':' @ integer (0)' / / random integer 'float':' @ float (1,100,3,6)', / / random floating point number, 'character':' @ character ("upper")', / / a random character 'string':' @ string ("lower", 5,20)', / / a random string 'range':' @ range (1,10,2)', / / an integer array Step size is 2}]}) / / console.log (basicData) Let Date = Mock.mock ({'dateList | 10 minutes: [{' date':'@ date', 'date-yyyy-MM-dd':' @ date (yyyy-MM-dd)', 'date-yy-MM-dd':' @ date (yy-MM-dd)', 'date-y-MM-dd':' @ date (y-MM-dd)' 'date-y-M-d':'@ date (y-M-d)', 'line-through':'--', 'timessss':' @ time', / / Random time string 'time-format':' @ time ()', / / indicates the format of the generated time string, default: 'HH:mm:ss', 'time-format-1':' @ time ("A HH:mm:ss")', 'time-format-2':' @ time ("a HH:mm:ss")', 'time-format-3':' @ time ("HH:mm:ss")' 'time-format-4':' @ time ("H:m:s")', 'datetime':' @ datetime ("yyyy-MM-dd A HH:mm:ss")', / / returns a random date and time string 'dateNow':' @ now ("second")'/ / get the current full time}]}) / / console.log (Date) Let imageList = Mock.mock ({'imageList | 5colors: [{' id | + 1picture: 1, 'img':' @ image',// generates a random image address, 'img-1':' @ image ("200x100", "# 000", "# fff", "png", "Mock.js")', / / generates a 20000100 with background color # 000 Foreground color # fff, format png, picture of text mock.js}]}) / / console.log (imageList) Let paragraph = Mock.mock ({'paragraphList | 5 sentences: [{' id | + 1 sentences: 1, 'paragraph2':' @ cparagraph (2)', / / generate a Chinese text of 2 sentences, 'paragraph3':' @ paragraph (3)', / / generate an English text of 3 sentences' title':'@ title' / / randomly generate an English title 'ctitle':' @ ctitle', / / randomly generate a Chinese title}]}) / / console.log (paragraph) Let name = Mock.mock ({'nameList | 5 words: [{' id | + 1 words: 1, 'name':' @ name', / / English name, 'cname':' @ cname', / / Chinese name}]}) / / console.log (name) Let webList = Mock.mock ({'webList | 5 domains: [{' id | + 1 domains: 0, 'url':' @ url ("http", "baidu.com")', / / url: http://www.baidu.com 'protocol':' @ protocol', / / randomly generate a url protocol 'domain':' @ domain', / / randomly generate a domain name 'email':' @ email', / / randomly generate an email address, 'ip':' @ ip' / / randomly generate an ip address}]}) / / console.log (webList) Let address = Mock.mock ({'addressList | 5 cities: [{' id | + 1 regions: 1, 'region':' @ region', / / generate a theater 'province':' @ province', / / generate a province 'city':' @ city', / / generate a city 'country':' @ country', / / a county 'zip':' @ zip' / / Postal Code}]}) console.log (address) Analog Interface

Mock.mock (rurl, rtype, data)

Describe the following three parameters:

Rurl: request path, either relative or absolute

Rtype: request method, such as get post put delete, etc.

Data: simulation data to be returned

For example:

Import React, {useEffect} from 'react'import Mock from' mockjs'import axios from 'axios'Mock.mock (' / mock/usermsg', 'get', {code:' 0mm, msg: 'success',' list | 5 minutes: [{name:'@ name', age:'@ integer (18) 25)'}]}) const DemoMock = () = > {useEffect (async ()) = > {const res = await axios ('/ mock/usermsg') console.log (res.data)}) return hello react} export default DemoMock

The returned result:

At this point, I believe you have a deeper understanding of "how to use the mockjs method in react". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report