搭建React脚手架
1.全局安装:npm install create-react-app -g
2.创建项目:create-react-app hello-react
3.运行:npm start
生命周期
挂载
1.constructor()
2.getDerivedStateFromProps()
3.render() //初始化渲染或更新渲染调用
4.componentDidMount() //发送请求
更新
1.getDerivedStateFromProps()
2.shouldComponentUpdate()
3.render()
4.getSnapshotBeforeUpdate()
5.componentDidUpdate()
卸载
1.componentWillUnmount() //做收尾工作,比如:清除定时器
事件传参
都是通过回调函数,有两种写法
第一方式:
<h3 onClick={this.click(1,2,3)}>Home</h3>
click = (a,b,c) => {
return() => {
console.log(a,b,c);
}
}
第二种方式:
<h3 onClick={() => this.click(1,2,3)}>Home</h3>
click = (a,b,c) => {
console.log(a,b,c);
}
函数式组件变量的声明和修改(useState)
声明:
参数说明:第一个参数是变量名,第二个参数是修改方法
const [count,setCount] = React.useState(0);
修改:
function add(){
// 第一种写法
// setCount(count+1)
// 第二种写法
setCount((c) => count + 1);
}
函数式组件的生命周期和监听(useEffect)
React.useEffect(() => {
// 可以执行网络请求,以及监听属性
let timer = setInterval(() => {
setCount((count) => count + 1);
}, 500)
console.log('监听的作用域在这里触发');
// 执行收尾工作
return () => {
clearInterval(timer);
};
}, [count]); //如果指定的是[],只会在第一次render()后执行
propTypes类型验证、defaultProps默认值
import propTypes from "prop-types"
static propsTypes = {
show:propTypes.bool
}
static defaultProps = {
show:true
}
ref(useRef)
语法:const myRef = React.useRef()
绑定:<input type="text" ref={myRef} />
使用:alert(myRef.current.value)
ref的使用
1.字符串
html: <input ref="input1" type="text" />
js: this.refs.input1.value
2.回调函数
html: <input ref={c => this.input1 = c} type="text" />
js: this.input1.value
3.React.createRef()
React.createRef()是一个ref所标识的容器,一个容器只能存放一个数据
声明容器:myRef1 = React.createRef()
绑定容器:<input ref={this.myRef1} type="text" />
使用: this.myRef1.current.value
卸载组件
const root = ReactDOM.createRoot(document.getElementById("root"));
root.unmount();
BrowserRouter与HashRouter的区别
1.底层原理不一样
BrowserRouter使用的是H5的history API,不兼容IE9及以下版本
HashRouter使用的是URL的哈希值
2.path表现形式不一样
BrowserRouter的路径没有‘#’
HashRouter的路径有‘#’4
3.刷新后对路由state参数影响
BrowserRouter没有影响
HashRouter路由state参数会丢失
4.备注:HashRouter可以解决一些路径相关的错误