0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

5-React 组件通信 useEffect

Posted at

image.png

一:父传子基础实现

image.png
1.父组件中通过给标签绑定一个属性,=后面绑定传递的数据
2.子组件中设置props的参数,在参数中会包含着父组件传递过来的所有数据
image.png

二:父传子props说明

image.png

三:父传子children说明

image.png

四:子传父实现

在子组件中调用父组件中的函数并传递实参
image.png
image.png

五:使用状态提升实现兄弟组件通信

image.png

// 1.通过子传父 A-> App
// 2.通过父传子 App-> B

function A({onGetAName}){
  // Son组件中的数据
  const name = "this is A name"
  return (
     <div>
      this is A compnent,
      <button onClick= {()=>onGetAName(name)}>send</button>
      </div>
  )
}

function B({name}){
  return (
     <div>
      this is B compnent
      {name}
      </div>
  )
}

function App() {
  const [name, setName] = useState("")
  const getAName = (name) =>{
    console.log(name)
    setName(name)
  }
  return (
    <div>
      this is App
     <A onGetAName = {getAName}/>
     <B name={name}/>
    </div>
  )
}

export default App;

六:使用context机制跨层传递数据

image.png

//App -> A -> B

import { useContext } from "react"

// 1.createContext方法创建一个上下文对象
const MsgContext = createContext()
// 2.在顶层组件 通过Provider组件提供数据

// 3.在顶层组件 通过useContext钩子函数使用数据

function A(){
  return (
     <div>
      this is A compnent,
      <B />
      </div>
  )
}

function B(){
  const msg = useContext(MsgContext)
  return (
     <div>
      this is B compnent,{msg}
      </div>
  )
}

function App() {
  const msg = "this is app msg"
  return (
    <div>
      <MsgContext.Provider value={msg}>
         this is App
         <A />
      </MsgContext.Provider>
    </div>
  )
}
export default App;

七:useEffect

1.概念理解和基础使用

image.png
image.png

import { useEffect, useState } from "react";

const URL = "  "
function App() {
  // 创建一个状态数据
  const [list,setList] = useState([])
  useEffect(()=>{
    // 额外的操作 获取频道列表
    async function getList(){
       const res = await fetch(URL)
       const jsonRes = await res.json()
       console.log(jsonRes)
       setList(jsonRes.data.channels)
    }
    getList()
  },[])
  return (
    <div>
         this is App
         <ul>
          {list.map(item => <li key={item.id}>{item.name}</li> )}
         </ul>
    </div>
  )
}
export default App;

2.不同依赖项说明

image.png

import { useEffect, useState } from "react";

function App() {
  // 1.没有依赖项 初始+组件更新
  const [count, setCount] = useState(0)
  useEffect(() =>{
    console.log("副作用函数执行了")
  })
  return (
    <div>
         this is App
         <button onClick ={()=>setCount(count +1)}>+{count}</button>
    </div>
  )
}
export default App;
import { useEffect, useState } from "react";

function App() {
  // 2.传入空数组依赖  初始执行一次
  useEffect(()=>{
    console.log("副作用函数执行了")
  },[])
  return (
    <div>
         this is App
         <button onClick ={()=>setCount(count +1)}>+{count}</button>
    </div>
  )
}
export default App;
import { useEffect, useState } from "react";

function App() {
  const [count,setCount] = useState(0)
  // 3.传入特定依赖项  初始 + 依赖项变化时执行
  useEffect(()=>{
    console.log("副作用函数执行了")
  },[count])
  return (
    <div>
         this is App
         <button onClick ={()=>setCount(count +1)}>+{count}</button>
    </div>
  )
}
export default App;

3.清除副作用

在第一个函数的末尾return一个新函数,在里面清除副作用
组件卸载时自动执行
image.png

import { useEffect, useState } from "react";

function Son(){
  // 1.渲染时开启一个定时器
  useEffect(()=>{
     const timer = setInterval(()=>{
      console.log("定时器执行中")
     },1000)

     return () =>{
      // 清除副作用 组件卸载时
      clearInterval(timer)
     }
  },[])
  return <div>this is son</div>
}

function App() {
  // 通过条件渲染模拟组件卸载
  const [show,setShow] = useState(true)
  return (
    <div>
         {show && <Son />}
         <button onClick ={()=>setShow(false)}>卸载Son组件</button>
    </div>
  )
}
export default App;

八:自定义hook实现

image.png

import { useEffect, useState } from "react";

// 封装自定义hook

// 1.声明一个以use打头的函数
// 2.在函数体内封装可复用的逻辑 只要是可复用的逻辑
// 3.把组件中用到的状态或者回调return出去 以对象或者数组
// 4.在哪个组件中要用到这个逻辑,就执行这个函数,解构出来状态和回调进行使用
function useToggle(){
  // 可复用的逻辑代码
  const [value,setValue] = useState(true)
  const toggle = ()=>setValue(!value)

  // 哪些状态和回调函数需要在其他组件中使用 return
  return{
    value,
    toggle
  }
}

function App() {
  const {value, toggle} = useToggle()
  return (
    <div>
        {value && <div>this is div</div>}
         <button onClick ={toggle}>toggle</button>
    </div>
  )
}
export default App;

九:reacthooks使用规则说明

1.组件外使用

2.if for组件内部函数

image.png

十:案例优化

image.png

1. 使用useEffect获取数据

image.png
①安装json-server

npm i json-server -D

准备一个json文件,放到根目录下src-db.json
image.png
创建命令,启动服务
image.png
②安装Axios

npm install axios
// 获取接口数据渲染
const [commentList, setCommentList] = useState([])

useEffect(()=>{
// 请求数据
async  function getList(){
  // axios请求数据
  const res = await axios.get("http://localhost:3004/list")
  setCommentList(res.data)
  }
  getList()
},[])

2. 自定义hook封装请求逻辑

image.png

// 封装请求数据的hook
function useGetList(){
// 获取接口数据渲染
const [commentList, setCommentList] = useState([])

useEffect(()=>{
// 请求数据
async  function getList(){
  // axios请求数据
  const res = await axios.get("http://localhost:3004/list")
  setCommentList(res.data)
  }
  getList()
},[])
}

return {
  commentList,
  setCommentList
}

const {commentList,setCommentList} = useGetList()

3. 评论item组件封装

image.png

// 封装item组件
function Item({item}){
 return(
  <div key={item.rpid} className="reply-item">
  </div>
 )
}

// 原来评论项
{commentList.map(item => <Item key={item.id} item={item}/>)}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?