这个特定的 ReactJs 代码如何执行初学者问题?

2022-01-20 00:00:00 reactjs fetch javascript

我是初学者,正在阅读大量代码,现在我想知道下面的代码
我了解这段代码在做什么,我需要澄清的是代码流.

我在运行它时看到图像加载:

  1. React 是从上到下执行代码吗?
  2. PlaceholderImages 异步获取图像正确,但如果需要时间,App 组件是否会开始渲染而没有图像?如果是这样,我看不到任何会通知 AppsetState.我可能弄错了!

此代码来自此沙盒.

这是 index.js

从react"导入反应;从react-dom"导入 ReactDOM;从./Masonry"导入砌体;从./VerticalMasonry"导入 VerticalMasonry;从lodash"导入{样本,uniqueId};从./PlaceholderImages"导入 PlaceholderImages;从./ItemRenderer"导入ItemRenderer;PlaceholderImages().then(图像 => {功能添加项目(数量= 10){return new Array(amount).fill("").map(i => {常量 id = uniqueId();常量图像 = 样本(图像);常量宽度 = 480;常量高度 = Math.round((480/image.width) * image.height);const imageUrl = `https://picsum.photos/${width}/${height}?image=${图像.id}`;返回 {ID,关键:身份证,比率:1/(image.width/image.height),背景图片:`url(${imageUrl})`,背景:`rgb(${Math.ceil(Math.random() * 256)}, ${Math.ceil(数学随机()* 256)}, ${Math.ceil(Math.random() * 256)})`,标题:Lorem ipsum dolor sit amet",描述:在 vero eos et accusam et justo duo dolores et ea rebum.Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."};});}让项目 = addItems();类 App 扩展 React.Component {状态 = {列:3,物品:物品,排水沟:16,外排水沟:是的,调试:是的,垂直:真};添加项目(){这个.setState({项目:this.state.items.concat(addItems(20))});}使成为() {常量 {项目,宽度,排水沟,外排水沟,调试,垂直的,全屏} = this.state;常量 LeComponent = 垂直 ?砌体:垂直砌体;返回 (

这是 PlaceholderImages.js

从axios"导入axios;从lodash"导入 { sampleSize };导出默认异步()=>{return new Promise((resolve, reject) => {axios.get("https://picsum.photos/list").then(res => {控制台.log(res.data[0]);返回解析(sampleSize(res.data,50));});});};

解决方案

PlaceholderImages().then(images => {...

首先进入你的堆栈的是方法PlaceholderImages.因此,您应该查看它的代码.

您将看到它返回一个带有两个参数的新 Promise:2 个回调函数,一个用于成功(解决),另一个用于 API 请求失败(拒绝).当您使用 axios(第 3 方库)使用 GET 方法执行 HTTP 请求时,会发生 API 请求.

同样,您有一个异步函数,并且 .then() 方法仅在 axos.get() 返回时调用.如果它从不返回任何内容,您将永远不会执行 then() 函数.

此时,您的堆栈(LIFO 服务规则)将有以下方法来执行:

PlaceholderImages() ->匿名函数()* ->新的承诺()->axios.get();

PlaceholderImages() 直到所有其他方法都执行完毕后才会执行.如果 axios.get() 方法未能收集到所需的数据,一旦您返回到代码的 PlaceholderImages().then() 部分,您将不会没有要渲染的图像.因此,无论如何都不会渲染任何内容.

I'm a beginner and are reading lots of code and now I wonder about the below code
I understand what this code is doing what I need clarification on is the code flow.

I see images loading when I run it:

  1. Is React executing the code from top to bottom?
  2. The PlaceholderImages async get's the images right but will App Component start to render with out images if it takes time? If so I dont see any setState that will notify App. I probably get it wrong!

This code is from this Sandbox.

This is index.js

import React from "react";
import ReactDOM from "react-dom";
import Masonry from "./Masonry";
import VerticalMasonry from "./VerticalMasonry";
import { sample, uniqueId } from "lodash";
import PlaceholderImages from "./PlaceholderImages";
import ItemRenderer from "./ItemRenderer";

PlaceholderImages().then(images => {
  function addItems(amount = 10) {
    return new Array(amount).fill("").map(i => {
      const id = uniqueId();
      const image = sample(images);

      const width = 480;
      const height = Math.round((480 / image.width) * image.height);
      const imageUrl = `https://picsum.photos/${width}/${height}?image=${
        image.id
      }`;

      return {
        id,
        key: id,
        ratio: 1 / (image.width / image.height),
        backgroundImage: `url(${imageUrl})`,
        background: `rgb(${Math.ceil(Math.random() * 256)}, ${Math.ceil(
          Math.random() * 256
        )}, ${Math.ceil(Math.random() * 256)})`,
        title: "Lorem ipsum dolor sit amet",
        description:
          "At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."
      };
    });
  }

  let Items = addItems();

  class App extends React.Component {
    state = {
      columns: 3,
      items: Items,
      gutter: 16,
      outerGutter: true,
      debug: true,
      vertical: true
    };

    addItems() {
      this.setState({
        items: this.state.items.concat(addItems(20))
      });
    }

    render() {
      const {
        items,
        width,
        gutter,
        outerGutter,
        debug,
        vertical,
        fullscreen
      } = this.state;

      const LeComponent = vertical ? Masonry : VerticalMasonry;

      return (
        <div>
          <div
            style={{
              position: fullscreen && "absolute",
              zIndex: 2
            }}
          >
            <label htmlFor="gutter">Gutter</label>
            <input
              id="gutter"
              type="number"
              step={1}
              min={0}
              max={32}
              value={gutter}
              onChange={e => {
                this.setState({
                  gutter: parseInt(e.target.value)
                });
              }}
            />
            <button
              onClick={() => this.setState({ outerGutter: !outerGutter })}
            >
              Outer Gutter: {outerGutter ? "On" : "Off"}
            </button>
            <button onClick={() => this.setState({ debug: !debug })}>
              debug
            </button>
            <button onClick={() => this.setState({ vertical: !vertical })}>
              {vertical ? "Vertical" : "Horizontal"}
            </button>
            <button onClick={() => this.setState({ width: 360 })}>360</button>
            <button onClick={() => this.setState({ width: 480 })}>480</button>
            <button onClick={() => this.setState({ width: 640 })}>640</button>
            <button onClick={() => this.setState({ width: 728 })}>728</button>
            <button onClick={() => this.setState({ width: 960 })}>960</button>
            <button onClick={() => this.setState({ width: "100%" })}>
              100%
            </button>
            <button onClick={() => this.setState({ fullscreen: !fullscreen })}>
              {fullscreen ? "Fullscreen off" : "Fullscreen on"}
            </button>
          </div>
          <div
            style={{
              width,
              height: !fullscreen && 600,
              position: fullscreen ? "initial" : "relative",
              margin: "0 auto"
            }}
          >
            <LeComponent
              infinite
              items={items}
              itemRenderer={ItemRenderer}
              gutter={gutter}
              outerGutter={outerGutter}
              extraPx={0}
              debug={debug}
              rows={{
                0: 1,
                320: 2,
                480: 3,
                640: 4
              }}
              cols={{
                0: 1,
                360: 2,
                640: 2,
                960: 3,
                1280: 4,
                1400: 5,
                1720: 6,
                2040: 7,
                2360: 8
              }}
              onEnd={() => {
                this.addItems();
              }}
            />
            <style>
              {`body {
                background-color:  white;
              }`}
            </style>
          </div>
        </div>
      );
    }
  }

  const rootElement = document.getElementById("root");
  ReactDOM.render(<App />, rootElement);
});

This is the PlaceholderImages.js

import axios from "axios";
import { sampleSize } from "lodash";

export default async () => {
  return new Promise((resolve, reject) => {
    axios.get("https://picsum.photos/list").then(res => {
      console.log(res.data[0]);
      return resolve(sampleSize(res.data, 50));
    });
  });
};

解决方案

PlaceholderImages().then(images => {...

The first thing entering your stack here is the method PlaceholderImages. Thus, you should look at its code.

You will see it returns a new Promise that takes two arguments: 2 callback functions, one in case of success (resolve) and the other in case of failure (reject) of your API request. The API request happens when your perform a HTTP Request with the method GET using axios (a 3rd party library).

Again, you have an asynchronous function and the .then() method is only invoked once axos.get() returns something. If it never returns anything, you will never execute the then() function.

At this point, your stack (LIFO service discipline) will have the following methods to execute:

PlaceholderImages() -> anonymous function()* -> new Promise() -> axios.get();

PlaceholderImages() won't be executed until all the other methods are executed. If the axios.get() method fails to gather the desired data, once you are back to the PlaceholderImages().then() part of the code, you won't have any images to render. Thus, nothing will be rendered anyway.

相关文章