react笔记

1.创建:

在xx文件夹中建立项目(项目本身会重新在一个新的app-name中)

creat-react-app app-name

在src文件夹下创建组件文件夹,里面存放index.css和index.js,在index.js中定义组件

基本模板:

import React, { Component } from 'react'
import './index.css'

export default class Peiqi extends Component {
	render(){
		return (
			<div>
				xxx
			<div>
		)
	}
}

2.props组件传参:

父组件传子组件:

<Child a={number} b="string">
<Child {...state}>

子组件拿值:

const {a,b} = this.props

3.事件处理:

1.使用类似onClick的小驼峰命名的回调函数,

2.回调函数传参的方法,必须返回一个函数:

export default class Peiqi extends Component{
	
	const {id} = this.props
	
	showData = (id)=>{
		return (event)=>{
			let {target, value} = envent
			console.log(id, target, event)
		}
	}
	
	render(){
		return (
			<div>
				<button onClick={this.showData(id)}>Button</button>
			</div>
		)
	}
}

4.生命周期

1.render:初始化渲染或更新渲染调用

2.componentDidMount:开启监听, 发送ajax请求

3.componentWillUnmount:做一些收尾工作, 如: 清理定时器

5.jsx语法规范:

1.标签中混入JS表达式时要用{}, 包括指定标签的回调函数和Js变量

2.样式的类名指定不要用class,要用className。

3.内联样式,要用style={{key:value}}的形式去写。

4.组件名称必须大写,否则视为html标签

6.state

初始化直接在类中定义state:

class MyComponent{
 	state = {'a':1, 'b':2}
	render(){
		return (
			 <div>
			 	xxx
			 <div/>
		)
	}
}

读取state中的值 haha:

const {haha} = this.state

对state的值进行修改:

this.setState({isHot:!isHot})//改了哪个value就写对应的key

7.配置代理

在package.json中追加如下配置

"proxy":"http://localhost:5000"

8.消息订阅:

导入模块

import PubSub from 'pubsub-js'

发送消息:

PubSub.publish('msg-name',{isFirst:false,isLoading:true})

订阅消息

componentDidMount(){
	this.token = PubSub.subscribe('msg-name',(_,stateObj)=>{
		this.setState(stateObj)
	})
}

componentWillUnmount(){
	PubSub.unsubscribe(this.token)
}

9.axios使用

1.注意在get之后写的是poxy后面的内容

2.通过组件在componenetDidMount()中添加订阅 ==> 接受到消息,修改状态 ==> 在render中通过不同的状态返回不同的值实现loading

import axios from 'axios'
...
//发送请求前通知List更新状态
PubSub.publish('msg',{isFirst:false,isLoading:true})
axios.get(`/search/users2?q=${keyWord}`).then(
	response => {
		//请求成功后通知List更新状态
		PubSub.publish('msg',{isLoading:false,users:response.data.items})
	},
	error => {
		//请求失败后通知App更新状态
		PubSub.publish('msg',{isLoading:false,err:error.message})
	}
)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值