接上一条博客的内容,再次附上视频教程的学习地址
链接:https://www.bilibili.com/video/BV184411x7F9
上一篇文章链接:https://blog.csdn.net/AtalantaDavis/article/details/108245250
文章目录
第三章 react应用
create-react-ap创建react应用
react脚手架
react脚手架:用来帮助程序员快速创建一个基于xxx库的模板项目
* 包含了所有需要的配置
* 指定好了所有的数据以来
* 可以直接安装/编译/运行一个简单效果
react提供了一个用于创建react项目的脚手架库:create-react-app
项目的整体技术架构为:react+webpack+es6+eslint
使用脚手架开发的项目特点:模块化,组件化,工程化
package.json
包的配置文件
- dependencies:运行时依赖
react
react-dom - devDependencies:开发式依赖,编译打包时才需要。
默认有react-scripts - scripts
- 运行,打包
import
import React ,{Component} from 'react'
class App extends Component {
}
或
import React from 'react'
class App extends React.Component {
}
.gitignore
git版本控制忽略配置
/node_modules
/build
yarn.lock
下东西是通过yarn来下载的所以自动生成
创建过程
cnpm install -g create-react-app // 全局下载
create-react-app hello-react //
全局下载的以来的根目录
npm root -g
第四章 React Ajax
说明
- React不包含发送ajax请求的代码
- 前端需要ajax与后端进行交互
常用的ajax请求库
- jquery,较重
- axios:轻量级
- 封装XmlHttpRequest对象的ajax
- promise风格,{ .then()有这个的叫promise风格}
- 可以用在浏览器端和node服务器端
- fetch:原生函数,但老版本浏览器不支持
- 不再使用XmlHttpRequest对象提交ajax请求
- 为了兼容低版本的浏览器,可以引入兼容库fetch.js
示例编码
// 使用axios 发送异步的ajax请求
// 需引入axios
const url = `https://api.github.com/search2/repositories?q=r&sort=stars`
axios.get(url)
.then(response => {
const result = response.data
console.log(result)
const {name, html_url} = result.items[0]
this.setState({repoName:name, repoUrl: html_url})
})
.catch((error) => { // 处理出错
alert(error.message)
})
//使用fetch 原生,不需要引入
fetch(url)
.then(response => {
return response.json()
})
.then(data => {
const {name, html_url} = data.items[0]
this.setState({repoName:name, repoUrl: html_url})
})
第五章 技术总结
组件通信
方式一 通过props传递
- 共同的数据放在父组件上,特有的数据放在自己组件内部(state)
- 通过props可以传递一般数据和函数数据,只能一层一层传递
- 一般数据->父组件传递数据给子组件->子组件读取数据
- 函数数据->子组件传递数据给父组件->子组件调用函数
弊端,传给孙子比较麻烦
方式二 通过消息订阅(subscribe)传递->发布(publish)机制
工具库:PubSubJS
用法:PubSub.pulish(‘search’,‘value’) 发送数据
PubSub.subscribe('search',function(msg, searchName){
//绑定监听
})
多层组件的通信