2、react学习: react hooks简单使用

 1 import React,{ useState,useEffect } from 'react'
 2 function User(){
 3     const [date,setDate] = useState(new Date());
 4     const [date2,setDate2] = useState(new Date());//多个变量写多个useState
 5     useEffect(()=>{
 6         const timerId = setInterval(() => {
 7             setDate(new Date());
 8             setDate2(new Date())
 9         }, 1000);
10         return ()=>clearInterval(timerId);//组件卸载就执行return方法
11     })
12     return(
13         <React.Fragment>
14             <h1>user</h1>
15             <div>時間:{date.toLocaleTimeString()}</div>
16             <div>時間2:{date2.toLocaleTimeString()}</div>
17         </React.Fragment>
18     )
19 }
20 
21 export default User;

 Hooks版todolist:

官方文档:https://reactjs.org/docs/hooks-overview.html

使你在⽆需修改组件结构的情况下复⽤状态逻辑 可将组件中相互关联的部分拆分成更⼩的函数,

复杂组件将变得 更容易理解 更简洁、更易理解的代码

 1 import React,{useState, useEffect} from 'react'
 2 import { userInfo } from 'os'
 3 
 4 function Hookspages(props){
 5     const [fruits, setFruits] =  useState(['苹果','栗子'])
 6     return (<div>
 7              Hookspages
 8              <AddFruits addFruit={ item=> setFruits([...fruits, item])}/>
 9              <FruitsList fruits={fruits} setFruits={setFruits}/>
10            </div>)
11 }
12 
13 
14 function AddFruits({addFruit}){
15     const [name, setName] = useState("");
16     return(
17         <div>
18             <input value={name} onChange={(e)=>setName(e.target.value)} />
19             <button onClick={()=>addFruit(name)}>点击增加</button>
20         </div>
21     )
22 }
23 
24 
25 function FruitsList({fruits,setFruits}){
26 
27     const delcur = delIndx=>{
28         const tem = [...fruits];
29         tem.splice(delIndx,1);
30         setFruits(tem)
31     }
32 
33     return(
34         <div>
35         <ul>
36         {fruits.map((item,index)=>{
37           return <li key={`fruits${index}`} onClick={()=>delcur(index)}>{item}</li>
38         })}
39         </ul>
40         </div>
41     )
42 }
43 
44 export default Hookspages;

 

posted @ 2020-08-28 23:59  雪糕战士  阅读(254)  评论(0编辑  收藏  举报