React脚手架创建项目
React脚手架创建项目
React脚手架创建项目
一、使用脚手架创建的Hello React
1.安装依赖库
npm i -g create-react-app
2.使用命令创建项目
create-react-app hello-react
3.进入所创建的项目目录文件夹
cd hello-react
4.启动项目
yarn start // npm start
5.项目目录文件作用
7.简介完整的项目
public index.html
srcApp.jsindex.js
二、父子组件间数据传递
1.父组件向子组件传递数据props
<Header count={1} />// 子组件通过 this.props获取数据
2.子组件向父组件传递数据
这里利用了,函数在哪里定义,函数的作用域链就在哪里,但子组件调用函数时,就能向父组件传递数据,操作父组件中的数据了,但是将方法传递多层时,比较麻烦
a.先在父组件中定义操作数据的方法
b.父组件定义的方法通过传递props的方式传递给子组件
c.子组件调用通过调用props传递过来的方法,利用给方法传递参数的形式,传递给了父组件
三、任意组件间通信
类似与消息订阅与发布,使用了一个依赖库PubSubJS
1.依赖安装
yarn add pubsub-js
2.使用api
1)import PubSub from 'pubsub-js' //引入
// 消息定越
2)PubSub.subscribe('delete', function(data){ }); //订阅// 取消消息订阅
3)Pubsub.unsubscribe(pubsub) // 取消指定的订阅
4)PubSub.clearAllSubscriptions() //取消全部订阅// 消息发布api
5)PubSub.publish(StationStatisticsID, data) //发布消息
6)PubSub.publishSync(StationStatisticsID, data)
3.在React的使用
a.消息订阅
放在componentDidMount生命钩子上,一般
componentDidMount(){// 这里的token 类似于使用定时器返回的id,在取消特定定时器时需要用到,所以保留到了本组件实例上this.token = PubSub.subscribe('atguigu',(_,stateObj)=>{this.setState(stateObj)});}
b.取消消息订阅
放在componentWillUnmount生命钩子上
componentWillUnmount(){// PubSub.unsubscribe(this.token);PubSub.clearAllSubscriptions() //取消全部订阅}
c.发布消息
凡是需要发布消息的地方都可以使用,我这里展示的是请求成功后的消息发布
axios.get(`http://localhost:3000/api1/search/users?q=${searchEl.value}`).then(response => {PubSub.publish('atguigu', { userList: response.data.items, isLoading: false });},error => {PubSub.publish('atguigu', { isLoading: false, err: error.message });})
四、React 前后端通信
1.axios库的使用
对xhr的封装
a.安装依赖
yarn add axios
b.使用
import axios from 'axios'
axios.get(`http://localhost:3000/api1/search/users?q=${searchEl.value}`).then(response => {console.log(response.data);},error => {console.log(error.message);})
2.fetch使用
使用了关注分离的思想
a.基本使用promise
fetch(`http://localhost:3000/api1/search/users?q=${searchEl.value}`)
.then(response=>response.json()
).then(data=>console.log(data)
).catch(
error=>console.log(error.message)
)
b.配合async语法使用
search = async () => {// 关注分离try {const response = await fetch(`http://localhost:3000/api1/search/users?q=${searchEl.value}`);const data = await response.json();PubSub.publish('atguigu', { userList: data.items, isLoading: false });} catch (error) {PubSub.publish('atguigu', { isLoading: false, err: error.message });}}
五、项目打包
1.打包
npm run build
2.简单运行到服务器
依赖serve库
npm -i serve -g
开启服务器
serve build
// 当在文件夹中时,可直接运行serve,开启服务器