文章目录
一、useContext
对比传统父子组件传值
1.useContext官方介绍
2.传统类组件使用组件属性、props
等传值
创建新的OriginChildren.js
文件(用来接收值的子组件)
import React, { Component } from 'react';
export default class OriginChildren extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<h1>我是子组件</h1>
<p>我是父组件传过来的射击次数{this.props.count}</p>
</div>
);
}
}
修改OriginExample.js
的代码(注意注释)
import React, { Component } from 'react';
import OriginChildren from './OriginChildren'; //父组件引入自组件OriginChildren
export default class OriginExample extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
}
}
componentDidMount(){
//组件挂载完成
console.log(`组件挂载完成=>你射击了${this.state.count}次!`)
}
componentDidUpdate(){
//组件更新完成
console.log(`组件更新完成=>你射击了${this.state.count}次!`)
}
//射击事件
ShootClick = () => {
this.setState({
count:this.state.count+1
})
}
render() {
return (
<div>
<h1>我是父组件</h1>
<h2>原始类继承component写法</h2>
<p>你已经射击了{this.state.count}次!</p>
<button onClick={this.ShootClick}>射击</button>
<hr color="red"></hr>
{/* 将射击次数传值到子组件 */}
<OriginChildren count={this.state.count}></OriginChildren>
</div>
);
}
}
运行结果:(原始props传值方式传值成功)
3.使用useContext
跨越组件层级共享数据(与Redux类似)
Context
的作用通俗点就是数据上下文,为他所包含的组件提供全局共享数据
创建一个新的
HooksUseContext.js
组件做父组件
//函数式声明快捷键 rfc
import React ,{useState,createContext}from 'react';
import HooksChildren from './HooksChildren'; //引入子组件
//------关键代码------
export const CountContext = createContext(); //在这里使用导出是为了在子组件解析数据使用
export default function HooksUseContext() {
const [count, setCount] = useState(0)
return (
<div>
<h1>React Hooks 写法</h1>
<p>你已经射击了{count}次!</p>
<button onClick={()=>{setCount(count+1)}}>射击</button>
{/* createContext关键代码 这段代码的意思就是将count变量允许跨越层级使用 与redux 类似 */}
<CountContext.Provider value={count}>
{/* 需要注意的是将需要用到context的组件放入 CountContext 标签内部*/}
<HooksChildren/>
</CountContext.Provider>
</div>
)
}
创建一个新的
函数式子组件:HooksChildren.js
import React ,{useContext}from 'react'
import {CountContext} from "./HooksUseContext"
export default function HooksChildren() {
const count = useContext(CountContext)
return (
<div>
<h1>我是函数式子组件</h1>
<h2>我是父组件传过来的射击次数{count}</h2>
</div>
)
}
运行结果:(这里已经实现透传成功)
二、useReducer介绍和使用
1.官方介绍
useReducer的使用(类似于useState)
创建一个新的
HooksUseReducer.js
来使用useReducer
import React, { useReducer } from 'react'
export default function HooksUseReducer() {
const [count, dispatch] = useReducer((state, actionType) => {
switch (actionType) {
case "expense":
return state - 1000
case "work":
return state + 100000
default:
break
}
}, 0)
return (
<div style={{margin:"100px 0"}}>
<p>你的银行卡余额还有:{count} 元!</p>
<button onClick={()=>{dispatch("expense")}}>消费</button>
<button onClick={()=>{dispatch("work")}}>挣钱</button>
</div>
)
}
执行结果:
温故才知新