条件渲染
{this.state.flag && <p>你好</p>} // 短路原则{this.state.flag ? <p>你好</p> : ''} // 三目运算符
- 案例
实现:页面加载时显示loading…3秒后内容自动出现,点击按钮再次进入loading…状态,3秒后再显示内容
import { Component } from 'react'export default class App extends Component {constructor() {super()this.state = {content: ['a', 'b', 'c', 'd'],flag: true}}componentDidMount() {setTimeout(() => {this.setState ({flag: !this.state.flag})}, 3000)}Updata=()=>{this.setState({flag:!this.state.flag},()=>{setTimeout(()=>{this.setState({flag:!this.state.flag})},2000)})}render() {const { flag, content } = this.stateif (flag) {return (<>loading...</>)} else {return (<><button onClick={this.Updata}>刷新</button><ul>{content.map((item, index) => {return (<li key={index}>{item}</li>)})}</ul></>)}}}
列表渲染
通过 数据.map(callback) return 返回节点节点内容使用单{}语法渲染
import { Component } from 'react'export default class App extends Component {constructor() {super()this.state = {people: [{id: 1,name: 'syukinmei',age: 21}, {id: 2,name: 'ebiebi',age: 18}],}}render() {const { people } = this.statereturn (<div>{people.map(person => {return (<dl key={person.id}><dt>{person.name}</dt><dd>age: {person.age}</dd></dl>)})}</div>)}}
- 案例
实习:点击按钮发送数据请求,有loading效果,请求成功渲染数据
import { Component } from 'react'export default class App extends Component {constructor() {super()this.state = {list: [], // 必须写数组flag: false}}getData = () => {this.setState({flag:true})fetch('http://59.110.226.77:3000/api/category').then(data => data.json()) // 数据格式化处理.then(res => {this.setState({flag:false,list: res.data.data})}).catch(error => Promise.reject(error))}render() {const { list,flag } = this.statereturn (<div><button color='red' onClick={this.getData}>发生数据请求</button>{flag&&<div>loading...</div>}{list.length ? <ul>{list.map((item, index) => <li key={index}>{item.name}</li>)}</ul>:null}</div>)}}
Line6中list初始值必须是空数组,不能是null或者空字符串,因为Line33中map的使用前提是list必须是个数组
this.state = {list: null,flag: false}{list.list.map((item, index) => <li key={index}>{item.name}</li>)}// 如果list不是写成数组 需要做判断list是否存在
