问题描述
我是初学者,正在阅读大量代码,现在我想知道下面的代码
我了解这段代码在做什么,我需要澄清的是代码流.
我在运行它时看到图像加载:
- React 是从上到下执行代码吗?
- PlaceholderImages 异步获取图像正确,但如果需要时间,
App组件是否会开始渲染而没有图像?如果是这样,我看不到任何会通知App的setState.我可能弄错了!
此代码来自此沙盒.
这是 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:
- Is React executing the code from top to bottom?
- 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.
这篇关于这个特定的 ReactJs 代码如何执行初学者问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End
相关推荐
业务场景:使用update语句去更新数据库字段。 原因:update接收值不正确。原来代码: $query = "UPDATE student SET date = now() WHERE id = $id";$result = $mysqli-query($query2) or die($mysqli-error); // 问题出现了在这句 $data = $result-fetch_ass...
2024-12-13
前端开发问题
136
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22
前端开发问题
182
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18
前端开发问题
301
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17
前端开发问题
437
如果你想在 layui 的 table 列表中增加 edit=date 属性但不生效,可能是以下问题导致的: 1. 缺少日期组件的初始化 如果想在表格中使用日期组件,需要在页面中引入 layui 的日期组件,并初始化: script type="text/javascript" src="/layui/layui.js"/scrip...
2024-06-11
前端开发问题
455
问题描述: 我需要在我的应用程序中验证一个文本字段。它既不能包含数字,也不能包含特殊字符,所以我尝试了这个正则表达式:/[a-zA-Z]/匹配,问题是,当我在字符串的中间或结尾放入一个数字或特殊字符时,这个正则表达式依然可以匹配通过。 解决办法: 你应...
2024-06-06
前端开发问题
165
热门文章
1错误 [ERR_REQUIRE_ESM]:不支持 ES 模块的 require()
2vue中yarn install报错:info There appears to be trouble with you
3为什么 Chrome(在 Electron 内部)会突然重定向到 chrome-error://chromewebdat
4“aria-hidden 元素不包含可聚焦元素"显示模态时的问题
5使用选择器在 CSS 中选择元素的前一个兄弟
6js报错:Uncaught SyntaxError: Unexpected string
7layui怎么刷新当前页面?
8将模式设置为“no-cors"时使用 fetch 访问 API 时出错
热门精品源码
最新VIP资源
1多功能实用站长工具箱html功能模板
2多风格简历在线生成程序网页模板
3论文相似度查询系统源码
4响应式旅游景点宣传推广页面模板
5在线起名宣传推广网站源码
6酷黑微信小程序网站开发宣传页模板
7房产销售交易中介网站模板
8小学作业自动生成程序


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)