React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React for循环

React中的for循环解读

作者:越来越好。

这篇文章主要介绍了React中的for循环解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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 src="./js/react.development.js"></script>
    <script src="./js/react-dom.development.js"></script>
    <script 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
  })

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文