zheng 5 dni temu
rodzic
commit
cf13eff59d

+ 6 - 2
21.react/高阶/project3/src/App.jsx

@@ -1,14 +1,18 @@
 import './App.css'
 import UseLearnState from './components/UseLearnState'
 import UseLearnEffect from './components/UseLearnEffect'
+import UseDemo from './components/UseDemo'
 import { useState } from 'react'
+
+
 function App() {
   const [isShow, setIsShow] = useState(true)
   return (
     <>
       <h1>首页</h1>
-      {/* <UseLearnState /> */}
-      {isShow ? <UseLearnEffect /> : '无内容'}
+      <UseLearnState />
+      {/* {isShow ? <UseLearnEffect /> : '无内容'} */}
+      {/* {isShow ? <UseDemo /> : '无内容'} */}
     </>
   )
 }

+ 39 - 0
21.react/高阶/project3/src/components/UseDemo.jsx

@@ -0,0 +1,39 @@
+import { useEffect, useState } from "react";
+
+function UseDemo() {
+    const [now, setNow] = useState(new Date());
+    const [count, setCount] = useState(1);
+    // 错误:不可以在每一次渲染 模式下 修改useState的值 陷入无限循环
+    useEffect(() => {
+        // setNow(new Date())
+        if (count < 4) {
+            setCount(count + 1)
+        }
+    })
+    // useEffect(() => {
+    //     const timer = setInterval(() => {
+    //         setNow(new Date())
+    //     }, 1000)
+    //     return () => {
+    //         console.log("卸载");
+    //         clearInterval(timer);
+    //     }
+    // }, [])
+    // 不可以在依赖项中直接修改 否则  陷入无限循环
+    // 因为缺少边界
+    // useEffect(() => {
+    //     // setNow(new Date())
+    //     if (count < 4) {
+    //         setCount(count + 1)
+    //     }
+    // }, [count])
+    return (
+        <div>
+            <h1>时钟</h1>
+            <h2>Count:{count}</h2>
+            <h3>当前时间:{now.toLocaleTimeString()}</h3>
+        </div>
+    )
+}
+
+export default UseDemo;

+ 1 - 1
21.react/高阶/project3/src/components/UseLearnEffect.jsx

@@ -25,7 +25,7 @@ function UseLearnEffect() {
         // 模式三:依赖变化执行时候触发 相当于componentDidUpdate [xxx] 发生变化 触发
         console.log("变化了")
         document.title = `点击了${count}次`
-    }, [count])
+    }, [count, num])
 
     // useEffect(() => {
     //     // 模式三:多个依赖变化执行时候触发 相当于componentDidUpdate [xxx] 发生变化 触发

+ 9 - 3
21.react/高阶/project3/src/components/UseLearnState.jsx

@@ -1,5 +1,6 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
 function UseLearnState() {
+    // this.setState 18+ 异步 18前同步异步都可 看使用方式
     // 字段名 修改字段名的方法
     // const [xx,setXx] = useState(initialState)
     const [count, setCount] = useState(1);
@@ -36,11 +37,16 @@ function UseLearnState() {
         setCount((prevVal) => prevVal + 1)
         setCount((prevVal) => prevVal + 1)
     }
+    useEffect(() => {
+        console.log("触发")
+    }, [count, isOpen])
     // 自动批量处理
     function handleChange() {
-        setCount(count + 1)
-        setIsOpen(!isOpen)
         // 组件渲染了一次
+        // 18之后都触发一次 17前触发两次
+        // setCount(count + 1)
+        // setIsOpen(!isOpen)
+
         setCount(c => c + 1)
         setIsOpen(is => !is)
     }