ajax.js: import axios from 'axios' axios.post({}) .then((res)=>{console.log('axios 获取数据成功:',res) }) .catch((error)=>{console.log('axios 获取数据失败',error)}) 封装: // axios.defaults.withCredentials=true // axios.defaults.crossDomain=true const instancePost = axios.create({ baseURL: 'https://ip:port', method: 'post', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: [function (data) { let ret = '' for (let key in data) { ret += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&' } return ret }] //请求拦截器、响应拦截器 // headers: { // 'Content-Type': 'application/json' // }, // transformRequest: [function(data) { // data = JSON.stringify(data) // return data // }] }) return instancePost({ data: { usrName, pwd }, url: "/login" })
index.html:
<body> <div id="root"></div> </body>
index.jsx:
import React from 'react' import ReactDOM from 'react-dom' import RoutHandler from './router' ReactDOM.render(<RoutHandler />,document.getElementById('root'))
router.jsx:
import React, {Component} from 'react' import {Router, Route, Switch } from 'react-router-dom'; import { createHashHistory } from 'history';
render:const hashHistory = createHashHistory(); <Router history={hashHistory}> <Switch> <Route exact path="/" component={Login}/> <Route exact path="/login" component={Login}/> </Switch> </Router>
login.jsx:
import React, {Component} from 'react' import {Link} from 'react-router-dom';
<Link replace={false} to="/posthash">查看图片</Link> <a href='#/posthash'>去posthash</a> <button onClick={() => this.props.history.push('posthash')}>通过函数跳转</button> 或this.props.history.push({pathname: '/detail',state: {id: 3}}) 或this.props.history.goBack/goForward() console.log("参数:",this.props.match.params) console.log(this.props.history.location.state)
父组件:
class Father extends Component { constructor(props) { super(props); this.state={ inputValue:'' , list:["a","b","c"] }
inputChange=(e)=> {this.setState({inputValue:e.target.value})} addServer=(inputValue)=>{this.setState({list:[...this.state.list,inputValue]})} componentDid/WillMount(){} <input value={inputValue} onChange={(e)=>{this.inputChange(e)}}/> <Son content={{item:item,index:index}}或item={item} addServer={this.addServer.bind(this)}/> } export default Father
子组件:
addItem = (item) =>{this.props.addServer(item)}
const {item,index} = this.props.content或item = this.props.item <button onClick={()=>{this.deleteItem(item)}}>增加</button>
sync优先级:
import {flushSync} from "react-dom";
flushSync(()=>{})
加载数据中loading...:import React, {Component,Suspense} from 'react'
<Suspense fallback="loading data">{data}</Suspense>
懒加载css:import React, {Component,lazy} from 'react'
const LazyComponent = lazy(()=>{import './xx.css'})
<LazyComponent />
css滚动加载图片:content-visibility:auto;占位:contains-intrinsic-size:xxpx;