React | 青训营笔记

47 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 5 天

React的历史与应用:大厂都用react。可以进行移动应用开发、桌面应用开发。

react的设计思路:1、UI编程的痛点:状态更新,缺乏代码层面的封装,没有组件化;UI之间的数据依赖。2、组件内有状态,外部不可见。3、父组件可将状态传入组件内部。

响应式系统:监听事件,消息驱动。事件=>执行回调=>状态变更=>更新UI。

状态归属于两个节点向上寻找最近的祖节点。

React的写法

funtion x(){
   const [count,setCount] = useState(0)
   return (
      <div>
         {count}
         <button onClick={()=>setCount(count+1)}></button>
      </div>
   )
}

CSS-in-JS pnpm i styled-components

JSX语法:他返回一个js的对象,是createElement方法的语法糖, 可以像写html一样写js。标签中的js表达式需要用{}包含

state:是组件对象最基本的属性,组件被称为状态机,通过更新组件的state 来更新对应的页面。 props:组件标签的所有属性都保存在props中;作用:通过标签属性向外传递数据 ,组件内部不能修改props属性!

mount:挂载。组件被渲染到DOM中,卸载unmount,DOM中组件被删除。

生命周期:1、初始化:constructor()-componentWillMount() -render()-

componentDidMount() 一般在这个钩子中做初始化,发送网络请求,订阅要洗。

2、更新:shouldComponentUpdate(),componentWillUpdate(),render()渲染, componentDidUpdate()

3、销毁:componentWillUnmount() 收尾工作,关闭定时器等等。

react应用:使用create-react-app创建项目

一些 axios 的请求 axios.get('/user') axios.post('/user')

axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
  
  axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });