React中的for循环解读
短信预约 -IT技能 免费直播动态提醒
React中的for循环
记得要绑定key!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script class="lazy" data-src="./js/react.development.js"></script>
<script class="lazy" data-src="./js/react-dom.development.js"></script>
<script class="lazy" data-src="./js/babel.min.js"></script>
<title>例子2</title>
</head>
<body>
<div id="root1"></div>
<div id="root2"></div>
<div id="root3"></div>
</body>
<script type="text/babel">
//继承实例
window.onload = () => {
var arr = ["a", "b", "d", "e", "f"];
//第一种写法 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
ReactDOM.render(
<div>
{
arr.map((item, index) => {
return <div key={index}>{item}</div>
})
}
</div>,
document.getElementById("root1")
)
//第二种写法 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
var str = arr.map((item, index) => {
return <div key={index}>{item}</div>
})
ReactDOM.render(
<div>
{str}
</div>,
document.getElementById("root2")
)
//第三种写法 我们应该是最熟悉这种写法
var str=[];
for(let i=0;i<arr.length;i++){
str.push(<div key={i}>{arr[i]}</div>)
}
ReactDOM.render(
str,
document.getElementById("root3")
)
}
</script>
</html>
React死循环
原因1
修改状态函数写在副作用函数里面,修改状态函数会使整个函数式组件重新执行,相当于执行了以下代码
export default function App () {
const [num, setNum] = useState(5)
console.log(setNum)
document.title = '标题' + num
useEffect(() => {
// setNum(num + 5)
document.title = '标题' + num
})
const hClick = () => {
setNum(num + 5)
// useEffect(() => {
// // setNum(num + 5)
// document.title = '标题' + num
// })
// 错误×
// Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
// 1. You might have mismatching versions of React and the renderer (such as React DOM)
// 2. You might be breaking the Rules of Hooks
// 3. You might have more than one copy of React in the same app
// See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
}
return (<div>
num:{num}
<button type="button" onClick={() => {
// eslint-disable-next-line no-unused-expressions
hClick()
}}>每次加5</button>
</div>)
}
错误代码如下:
useEffect(() => {
// setNum(num + 5)
document.title = '标题' + num
})
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341