react快速复习

一、主要依赖

  • react、react-dom、
  • react-router,react-router-dom、
  • react-redux、redux、mobx、
  • axios、promise、fetch、
  • babel、es6、node、

二、使用方式

使用jsx主要依赖于babel、es6、react、react-dom

三大类组件:函数式组件hooks、类组件、jsx

 类组件:

  • 在render中return节点数据。
  • props使用:this.props.属性,只读
  • state:组件状态管理方式,在构造方法中 初始化this.state={},this.setState({...}),
  • 变量:以
    {this.state.data}
    方式嵌入到组件
  • 生命周期:componentWillUnmount 、componentDidMount
  • 组件的使用:<类名 data={...params,function} />

函数式组件:

jsx:

false, null, undefined, and true 是合法的子元素。但它们并不会被渲染

const element = <div>element</div>;

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

//state使用
 this.setState(state => ({
      clicks: state.count+ 1
    }));

this.setState((state) => {
  return {quantity: state.quantity + 1};
});

this.setState({},callback)//异步调用,替换上一个state中的属性

四、组件生命周期和元素渲染

数据流单向自上而下,state位于局部,其他组件一般无法访问。

生命周期

卸载
componentWillUnmount()
错误处理
static getDerivedStateFromError()
componentDidCatch()
更新
shouldComponentUpdate(nextProps, nextState)
forceUpdate() 
componentDidUpdate(prevProps) {
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}
初始化
constructor(props)
componentDidMount 网络请求

 static getDerivedStateFromError(error) {
    // 更新 state 使下一次渲染可以显降级 UI
    return { hasError: true };
  }

render

元素渲染

主要方式:diff算法

策略:组件算法、dom层级算法、element算法

虚拟节点Fragment:react提供,不会展示在dom树中

ReactDOM.createPortal

ReactDOM.render()
在return中可以使用{this.state.属性 && <element />}
{this.state.属性?<div>123</div: 1231}

五、this

在react组件中,this一般指向类本身或函数本身,不建议改变this指向,

传参:this绑定问题

map列表遍历,绑定key

六、受控组件和非受控组件

受控组件:通过限制表单的输入或状态改变事件的入口,改变state来作用于dom的value

非受控组件,不限制输入输出、通过ref等获取dom值

七、context和prop-type

const MyContext = React.createContext(defaultValue);
<MyContext.Provider value={/* 某个值 */}>

使用import PropTypes from 'prop-types';检查类型
App.propTypes = {
  children: PropTypes.element.isRequired
};

八、react顶层api

cloneElement()
isValidElement()
React.Children
createFactory()
React.createRef
React.forwardRef
React.Fragment
。。。

React 支持的 DOM 属性有:

accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap

九、hooks

  • useEffect
//useState


useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // 仅在 count 更改时更新

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, []); // 初始化


useEffect(() => {
  document.title = `You clicked ${count} times`;
}]); // state改变更新

useEffect 就是一个 Effect Hook,给函数组件增加了操作副作用的能力。它跟 class 组件中的 componentDidMount、componentDidUpdate 和 componentWillUnmount 具有相同的用途,只不过被合并成了一个 API

  • useRef
const ref = useRef(null);

<div ref={ref}>节点</div>
  •   useState
const [data,setData] = useState('init');
console.log(data); //init
setData('init1');
console.log(data);// init1
  • useContext(MyContext)
//接收 就近context容器包裹原则
const value = useContext(obj);
<div>{value.?}</div>

//使用
const obj= React.createContext(obj);


 <obj.Provider value={obj}>
      {...element}
 </obj.Provider>
  • memo

性能优化,慎重使用,因为仅作props浅层比较,阻止渲染。

import React, {useState} from 'react';
import { Button } from 'antd-mobile'
import './index.css';
import Model from "../../components/model";

const HomePage = () => {
    const [name, setName] = useState(0);
    const [sex, setSex] = useState([0]);
    const onClick = (value) => {
        setSex([value +1])
    }
    return (
        <div className="home-page">
            <Model name={name} />
            <Button onClick={() => setName(name+1)}>memo浅层</Button>
            <Button  onClick={() => onClick(sex[0]) }>memo深层{sex[0]}</Button>
        </div>
    )
}
export default HomePage;


import React,{memo} from 'react';
// 加上memo该组件只在props改变时刷新,不加会在父组件刷新时刷新,相当于懒加载
const Model = memo((props) => {
    console.log(props);
    const {name} = props;
    return (
        <div>{name}</div>
    )
})
export default Model;

  • useImperativeHandle+forwordRef

将ref暴露给父组件使用

  • 定时器
useEffect(() => {
  if (flag) {
    readTime = setInterval(() => {
      setCount((num) => {
        if (num === 0) {
          clearInterval(readTime);
          setFlag(!flag);
          return 0;
        }
        return num - 1;

      });
        return  clearInterval(readTime);//组件卸载
    }, 1000);
  }
}, [flag]);

const m =useCallback((node)=>{

},[]);

<div ref={m}></div>

十、redux

reducer

const defaultState = {
    data:"init data"
}
const reducer = (state=defaultState,action)=>{
   // ...
    return state.data+action.data ;
}

Store 是一个容器,存储要保存的state,要使用时,需要手动引入。

import { createStore } from 'redux';
const store = createStore(reducer);//reducer是一个自定义纯函数,主要用于放置修改数据的程序。

获取state需要

使用

const state = store.getState();//引入store

Action是一个数据变化构造对象,包含要传递的参数的触发动作和要传递的数据。

const action = {
  type: 'will do action',
  data: 'new data'
};

//然而实际开发中并不是只有一种action的type,可以构造成:
const NEW_ACTION = 'ADD DATA';

function CREATE_ACTION(DATA) {
  return {
    type: NEW_ACTION,
    DATA
  }
}

const action = CREATE_ACTION('INPUT DATA');
//使用时通过
store.dispatch(action);//触发数据变化
等介于:
store.dispatch({
  type: 'ADD DATA',
  DATA: 'INPUT DATA'
});
  • 在函数中直接return节点数据
  • props使用:在创建函数时,在function fun(props)中传入参数props,通过props.属性调用---只读。
  • state:通过从依赖‘react’中引入const [data,setData]UseState(),进行初始化页面状态,状态管理使用setData()。
  • 变量:以
    方式嵌入 ...等方式。
  • 组件的使用:<函数名 data={...params,function} />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百度一下吧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值