Get data from axios get_ Solve the problem that the page in Vue successfully renders data undefined

Posted by nadeemshafi9 on Fri, 17 Dec 2021 00:50:13 +0100

preface

This title is not easy to take.

This article requires the following knowledge:

https://zhuanlan.zhihu.com/p/260811233​zhuanlan.zhihu.com

Problem description

One of my recent functional requirements is to obtain the json file stored in COS through axios and render it to the page at the same time.

The problem is that axios can successfully obtain data and render components, but the console will report an error

[Vue warn]: Error in render: "TypeError: Cannot read property 'text' of undefined".

problem analysis

First of all, my situation is more complicated than the problems of bloggers I have found.

Part of my json file is as follows:

  
  1. {
  2. "0": {
  3. "headline": "How to quickly adjust the brightness of the display group?",
  4. "url": "zhuanlan.zhihu.com/p/259647484",
  5. "dateP": "2020-09-26T13:35:07.000Z",
  6. "dateM": "2020-09-26T13:37:24.000Z",
  7. "img": "https://pic2.zhimg.com/v2-8b58a57ba0923d23329abc16766da34c_r.jpg",
  8. "text": "preface Mac I don't know, but Windows Adjusting the brightness of the display is actually a very annoying thing. My monitor group is a 15.6 A 22 inch secondary screen, a 22 inch display and a 15 inch display.6 Inch laptop screen. Due to hardware reasons, adjust the brightness through the display itself"
  9. },
  10. "1": {
  11. "headline": "adopt Vue realization vw/vh Adaptive unit",
  12. "url": "zhuanlan.zhihu.com/p/257866252",
  13. "dateP": "2020-09-22T10:51:08.000Z",
  14. "dateM": "2020-09-22T10:51:08.000Z",
  15. "img": "https://pic4.zhimg.com/v2-8ac0ec7ef990ca579657ae5b8bea714c_r.jpg",
  16. "text": "Preface although there may be more responsive layouts now, I still think adaptive units are easier to use. For some framework UI Components, such as Vuetify,The use of adaptive units may not be supported, which will greatly affect the layout effect. The methods provided in this article can help you achieve this"
  17. },
  18. "2": {
  19. "headline": "how DIY Portable display?",
  20. "url": "zhuanlan.zhihu.com/p/257257464",
  21. "dateP": "2020-09-21T13:43:08.000Z",
  22. "dateM": "2020-09-21T13:52:32.000Z",
  23. "img": "https://pic1.zhimg.com/v2-7f27fabd9fc334d2c7e529561658b82f_r.jpg",
  24. "text": "Preface recently, I'm depressed to find a job. I'll write a few articles to relax. This article is long and has many knowledge points. It is recommended to collect or agree to leave a pointer for yourself (mistaken portable display). Portable display can be known by its name. It is a mobile display, so it should meet several major needs: low voltage power supply (relative to transmission"
  25. },

If you are curious about how this json file was obtained, you can visit:

LikeDreamwalker/zhihu-articles-api​github.com

And give me a star!

The problem with this json file is that it is multi-layered. In general, it is a simple one-dimensional array or a layer of objects.

Next, the key question is why axios has successfully obtained data and the component has been rendered, but it will report an error?

undefined means index [0] Text is not defined, but called again, that is, the index object is called when the page is rendered, but index [0] Text has not been defined, that is, axios has not got data yet.

Then the idea is very simple. Scheme 1 is that we try to write the index object in advance, that is, specify it in data

  
  1. index: {{text=null}}

In scheme 2, we let the corresponding component render the component after axios obtains the data.

Let me first explain that 1 and 1 are a solution, but in my case, I can't control how many objects there are, and each object has many properties. This solution can solve the symptoms but not the root cause. However, when you declare, you should declare according to the real structure of the object as much as possible. If you can't solve this problem like me, there are ways below.

Of course, if your object is simple, it's over here, which can be a solution.

Therefore, the problem becomes simple. The core is when axios obtains the data, and whether it is possible to obtain the data before the page is rendered.

When did axios get the data

There are two general uses of axios: one is placed in created, that is, before page rendering, and the other is placed in mounted, that is, after page rendering.

So we can try to write two cases:

  
  1. created() {
  2. console.log( "start");
  3. axios
  4. .get(
  5. "https://ldwid-1258491808.cos.ap-beijing.myqcloud.com/json/doNotUseThisJSON.json"
  6. )
  7. //For debugging local json
  8. //.get("http://localhost:8080/doNotUseThisJSON.json")
  9. .then( response => {
  10. _this.index = response.data;
  11. console.log(response.data);
  12. console.log(_this.index);
  13. console.log(_this.index[ 0]);
  14. });
  15. console.log( "created");
  16. },
  17. mounted() {
  18. console.log( "start");
  19. axios
  20. .get(
  21. "https://ldwid-1258491808.cos.ap-beijing.myqcloud.com/json/doNotUseThisJSON.json"
  22. )
  23. //For debugging local json
  24. //.get("http://localhost:8080/doNotUseThisJSON.json")
  25. .then( response => {
  26. _this.index = response.data;
  27. console.log(response.data);
  28. console.log(_this.index);
  29. console.log(_this.index[ 0]);
  30. });
  31. console.log( "mounted");
  32. }

Not surprisingly, you will find that these two situations will still throw undefined errors.

But this is contrary to the logic. Since I choose to get the data before page rendering, why do I still report an error?

Guess: network problem

Because axios is asynchronous, maybe the axios statement is actually executed when created, but due to network problems, the loading time is greater than the execution time of the statement, so the data obtained will be after the page rendering.

This guess is logical, but it is actually a problem with the understanding of JS asynchrony and life cycle. Please read the following article:

https://zhuanlan.zhihu.com/p/260811233​zhuanlan.zhihu.com

Instead of guessing, let's take a look at the specific execution sequence:

  
  1. beforeCreate() {
  2. console.log( "beforCreate");
  3. },
  4. created() {
  5. let _this = this;
  6. console.log( "start");
  7. axios
  8. // .get(
  9. // "https://ldwid-1258491808.cos.ap-beijing.myqcloud.com/json/doNotUseThisJSON.json"
  10. // )
  11. .get( "http://localhost:8080/doNotUseThisJSON.json")
  12. .then( response => {
  13. _this.index = response.data;
  14. console.log(response.data);
  15. console.log(_this.index);
  16. console.log(_this.index[ 0]);
  17. });
  18. console.log( "created");
  19. },
  20. beforeMount() {
  21. console.log( "beforMount");
  22. },
  23. mounted() {
  24. console.log( "mounted");
  25. }

Then we load the page:

The answer may be unexpected. Although the axios statement is placed under created, the actual execution is after mounted.

If you don't believe it, you can also put axios into other life cycles, which will still be the result.

Therefore, axios will get the data after the page is fully rendered. When you get the template string and replacement string on the rendering page, you will naturally report an error if you find that a non-existent attribute is referenced.

Can axios get data before page rendering

This requires knowledge of lifecycle and asynchrony:

https://zhuanlan.zhihu.com/p/260811233​zhuanlan.zhihu.com

First, axios is asynchronous. Since it is asynchronous, axios statements will not be accessed until all macro tasks are executed, and continue to be executed in the order of micro task queue. Therefore, axios can no longer get data before page rendering.

If axios is synchronized, when you fill in the wrong API or the API fails, the whole life cycle will be blocked and crash, and finally the page rendering will fail. But obviously, this is not possible in the development process.

If you still have obsession and think it is the above network environment problem, if it is true at this time, axios is actually another thread, parallel to the life cycle, but JavaScript is a single threaded language.

Here, the causal relationship of the whole problem should be very clear:

  • If you want index [0] For normal text parsing, we need to fill in the correct text attribute before parsing. At this time, you need to write the index directly or ask axios to fill in the correct text attribute before template parsing
  • Due to the life cycle, we know that axios must complete the acquisition before beforeMount
  • Due to the asynchronous nature of axios, axios cannot complete the acquisition before page rendering
  • If you want to do this, you must make axios execute in another thread, but JavaScript is a single threaded language

Problem solving

After we know the cause of the problem, the way to solve the problem becomes very simple.

We already know in our analysis that there are at least two ways to solve this problem. Let's now look at the second way.

Render the corresponding components after axios obtains the data

Here we use Vue's conditional rendering:

Conditional rendering - Vue js​cn.vuejs.org

Since we know that axios will execute after page rendering, we can artificially add a state to identify whether axios has obtained data. For the corresponding template, rendering will be performed only when the state is true.

If you are wondering why this can be achieved, you can take a look at the node reporting an error again. After beforeMount and before Mounted, that is, when the template is parsed into a template string and stored in memory, but has not been rendered on the page (or will be rendered on the page), Vue will not execute the template content that does not meet the rendering conditions:

So is v-if Lazy: if the condition is false at the initial rendering, nothing is done -- the conditional block does not start rendering until the condition first becomes true.

We modify the template content:

  
  1. <v-card-text v-if="status">
  2. {{ index[0].text }}
  3. </v-card-text>

Modify data:

  
  1. data: () => ({
  2. status: false ,
  3. index: {}
  4. }),

Modify axios:

  
  1. mounted() {
  2. let _this = this;
  3. axios
  4. . get(
  5. "https://ldwid-1258491808.cos.ap-beijing.myqcloud.com/json/doNotUseThisJSON.json"
  6. )
  7. .then(response => {
  8. _this.index = response. data;
  9. _this.status = true;
  10. });
  11. }

At this time, refresh the page again and no more errors will be reported.

Be sure to put the modification of status in then instead of mounted, otherwise it will still have no effect.

It should be reminded that the judgment condition used by many people to solve this problem is the attribute itself. The premise of using this attribute as the judgment condition is that the attribute exists. Otherwise, undefined will still be converted to false, and null will also be converted to false. The former will still report an error when used, and undefined will not change at this time, The reason why this page can still render data is that two-way binding makes this attribute value exist after the page is rendered, and the template content will be rendered naturally.

If you can declare such content, why not write the complete object directly? If the complete object is not easy to declare manually, why use the attribute value of the object as the judgment condition?

As for performance, I think it has little impact. After all, declaring more than one variable is not a very large amount of computation.

last

I don't know if you understand, but I think I have a new understanding of Vue and JavaScript after I climb out of this pit.

Topics: Vue Vue.js