React中的for循环解读.docxVIP

  • 0
  • 0
  • 约2.36千字
  • 约 4页
  • 2025-05-24 发布于四川
  • 举报

React中的for循环解读

目录React中的for循环React死循环原因1总结

React中的for循环

记得要绑定key!

!DOCTYPEhtml

htmllang=en

head

metacharset=UTF-8

metaname=viewportcontent=width=device-width,initial-scale=1.0

metahttp-equiv=X-UA-Compatiblecontent=ie=edge

scriptsrc=./js/react.development.js/script

scriptsrc=./js/react-dom.development.js/script

scriptsrc=./js/babel.min.js/script

title例子2/title

/head

body

divid=root1/div

divid=root2/div

divid=root3/div

/body

scripttype=text/babel

//继承实例

window.onload=()={

vararr=[a,b,d,e,f];

//第一种写法

ReactDOM.render(

div

arr.map((item,index)={

returndivkey={index}{item}/div

/div,

document.getElementById(root1)

//第二种写法

varstr=arr.map((item,index)={

returndivkey={index}{item}/div

ReactDOM.render(

div

{str}

/div,

document.getElementById(root2)

//第三种写法我们应该是最熟悉这种写法

varstr=[];

for(leti=0;iarr.length;i++){

str.push(divkey={i}{arr[i]}/div)

ReactDOM.render(

str,

document.getElementById(root3)

/script

/html

React死循环

原因1

修改状态函数写在副作用函数里面,修改状态函数会使整个函数式组件重新执行,相当于执行了以下代码

exportdefaultfunctionApp(){

?const[num,setNum]=useState(5)

?console.log(setNum)

?document.title=标题+num

?useEffect(()={

??//setNum(num+5)

??document.title=标题+num

?consthClick=()={

??setNum(num+5)

??//useEffect(()={

??//?//setNum(num+5)

??//?document.title=标题+num

??//})

??//错误×

??//Error:Invalidhookcall.Hookscanonlybecalledinsideofthebodyofafunctioncomponent.Thiscouldhappenforoneofthefollowingreasons:

??//1.YoumighthavemismatchingversionsofReactandtherenderer(suchasReactDOM)

??//2.YoumightbebreakingtheRulesofHooks

??//3.YoumighthavemorethanonecopyofReactinthesameapp

??//See/link/invalid-hook-callfortipsabouthowtodebugandfixthisprobl

文档评论(0)

1亿VIP精品文档

相关文档