React基礎知識2
3.React應用(基于react腳手架)
3.1 react腳手架
1.xxx腳手架: 用來幫助程式員快速創建一個基于xxx庫的模板專案
a.包含了所有需要的配置
b.指定好了所有的依賴
c.可以直接安裝/編譯/運行一個簡單效果
2.react提供了一個用于創建react專案的腳手架庫: create-react-app
3.專案的整體技術架構為: react + webpack + es6 + eslint
4.使用腳手架開發的專案的特點: 模塊化, 組件化, 工程化
3.2 創建專案并啟動
1.cnpm install -g create-react-app --全域安裝
2.create-react-app hello-react ---進入到目的路徑后開始創建專案
3.cd hello-react --進入到專案目錄
4.npm start ---啟動專案
執行第二條指令時,可能會非常慢,這是因為creact-react-app默認呼叫npm,把npm的register給永久設定過來即可,這樣使用cnpm或者npm就沒差別了
解決方法如下:
npm config set registry https://registry.npm.taobao.org
-- 配置后可通過下面方式來驗證是否成功
npm config get registry
3.3 react腳手架專案結構
npm root -g 查看全域的下載根目錄

4. react ajax
1.React本身只關注于界面, 并不包含發送ajax請求的代碼
2.前端應用需要通過ajax請求與后臺進行互動(json資料)
3.react應用中需要集成第三方ajax庫(或自己封裝)
---常用的ajax庫---
1.jQuery: 比較重, 如果需要另外引入不建議使用
2.axios: 輕量級, 建議使用
a.封裝XmlHttpRequest物件的ajax
b. promise風格
c.可以用在瀏覽器端和node服務器端
3.fetch: 原生函式, 但老版本瀏覽器不支持
a.不再使用XmlHttpRequest物件提交ajax請求
b.為了兼容低版本的瀏覽器, 可以引入兼容庫fetch.js
axios發送ajax請求
檔案鏈接:link
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script type="text/babel">
//1.定義組件
class Angle extends React.Component {
state = {
repoName: '',
repoUrl: ''
}
componentDidMount() {
//使用axios發送異步的ajax請求
const url = 'https://api.github.com/search/repositories?q=re&sort=stars'
axios.get(url)
.then(response => {
const result = response.data
//得到資料
const {name,html_url} =result.items[0]
//更新狀態
this.setState({repoName:name,repoUrl:html_url})
})
//列印錯誤資訊
.catch((error)=>{alert(error.message)})
}
render() {
const { repoName, repoUrl } = this.state
if (!repoName) {
return <h2>Loading...</h2>
} else {
return <h2>前端框架:<a href='javascript:void(0)'>{repoName}</a></h2>
}
}
}
//2.渲染組件標簽
ReactDOM.render(<Angle />, document.getElementById('example'))
</script>
</body>

fetch函式發送ajax請求
<body>
<div id="example"></div>
<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script type="text/babel">
//1.定義組件
class Angle extends React.Component {
state = {
repoName: '',
repoUrl: ''
}
componentDidMount() {
const url = 'https://api.github.com/search/repositories?q=re&sort=stars'
//2.使用fetch發送異步的ajax請求
fetch(url).then(response=>{return response.json()})
.then(data=>{
//得到資料
const {name,html_url}=data.items[0]
//更新狀態
this.setState({repoName:name,repoUrl:html_url})
})
}
render() {
const { repoName, repoUrl } = this.state
if (!repoName) {
return <h2>Loading...</h2>
} else {
return <h2>前端框架:<a href='javascript:void(0)'>{repoName}</a></h2>
}
}
}
//2.渲染組件標簽
ReactDOM.render(<Angle />, document.getElementById('example'))
</script>
</body>
5.組件間通信
方式1: 通過props傳遞
1.共同的資料放在父組件上, 特有的資料放在自己組件內部(state)
2.通過props可以傳遞一般資料和函式資料, 只能一層一層傳遞
3.一般資料-->父組件傳遞資料給子組件-->子組件讀取資料
4.函式資料-->子組件傳遞資料給父組件-->子組件呼叫函式
方式2: 使用訊息訂閱(subscribe)-發布(publish)機制
1.工具庫: PubSubJS
2.下載: npm install pubsub-js --save
3.使用:
import PubSub from 'pubsub-js' //引入
PubSub.subscribe('delete', function(data){ }); //訂閱
PubSub.publish('delete', data) //發布訊息
方式3: redux(詳情見下)
6.事件監聽
-----6.1 原生DOM事件
1--系結事件監聽
a.事件名(型別): 只有有限的幾個, 不能隨便寫
b.回呼函式
2- 觸發事件
a.用戶操作界面
b.事件名(型別)
c.資料()
-----6.2 自定義事件(訊息機制)
1-系結事件監聽
a.事件名(型別): 任意
b.回呼函式: 通過形參接收資料, 在函式體處理事件
2-觸發事件(編碼)
a.事件名(型別): 與系結的事件監聽的事件名一致
b.資料: 會自動傳遞給回呼函式
6.3 ES6常用新語法
1.定義常量/變數: const/let
2.解構賦值: let {a, b} = this.props import {aa} from 'xxx'
3.物件的簡潔表達: {a, b}
4.箭頭函式:
a.常用場景
* 組件的自定義方法: xxx = () => {}
* 引數匿名函式
b.優點:
* 簡潔
* 沒有自己的this,使用參考this查找的是外部this
5)擴展(三點)運算子: 拆解物件(const MyProps = {}, <Xxx {...MyProps}>)
6)類: class/extends/constructor/super
7)ES6模塊化: export default | import
7.react-router4
--------------7.1 react-router的理解------------
1.react的一個插件庫
2.專門用來實作一個SPA應用
3.基于react的專案基本都會用到此庫
-------------7.2 SPA的理解----------------------
1. 單頁Web應用(single page web application,SPA)
2. 整個應用只有一個完整的頁面
3. 點擊頁面中的鏈接不會重繪頁面, 本身也不會向服務器發請求
4. 當點擊路由鏈接時, 只會做頁面的區域更新
5. 資料都需要通過ajax請求獲取, 并在前端異步展現
------------7.3 路由的理解---------------------
-----1-什么是路由?
a.一個路由就是一個映射關系(key:value)
b.key為路由路徑, value可能是function/component
-----2-路由的分類
a.后臺路由: node服務器端路由, value是function, 用來處理客戶端提交的請求并回傳一個回應資料
b.前臺路由: 瀏覽器端路由, value是component, 當請求的是路由path時, 瀏覽器端前沒有發送http請求, 但界面會更新顯示對應的組件
------2-1 后臺路由
a.注冊路由: router.get(path, function(req, res))
b.當node接收到一個請求時, 根據請求路徑找到匹配的路由, 呼叫路由中的函式來處理請求, 回傳回應資料
------2-2 前端路由
a.注冊路由: <Route path="/about" component={About}>
b.當瀏覽器的hash變為#about時, 當前路由組件就會變為About組件
前端路由的實作
1.history庫
a.網址: https://github.com/ReactTraining/history
b.管理瀏覽器會話歷史(history)的工具庫
c.包裝的是原生BOM中window.history和window.location.hash
2.history API
a.History.createBrowserHistory(): 得到封裝window.history的管理物件
b.History.createHashHistory(): 得到封裝window.location.hash的管理物件
c.history.push(): 添加一個新的歷史記錄
d.history.replace(): 用一個新的歷史記錄替換當前的記錄
e.history.goBack(): 回退到上一個歷史記錄
f.history.goForword(): 前進到下一個歷史記錄
g.history.listen(function(location){}): 監視歷史記錄的變化
<body>
<p><input type="text"></p>
<a href="/test1" onclick="return push('/test1')">test1</a><br><br>
<button onClick="push('/test2')">push test2</button><br><br>
<button onClick="back()">回退</button><br><br>
<button onClick="forword()">前進</button><br><br>
<button onClick="replace('/test3')">replace test3</button><br><br>
<script type="text/javascript" src="https://cdn.bootcss.com/history/4.7.2/history.js"></script>
<script type="text/javascript">
let history = History.createBrowserHistory() // 方式一
// history = History.createHashHistory() // 方式二
// console.log(history)
function push (to) {
history.push(to)
return false
}
function back() {
history.goBack()
}
function forword() {
history.goForward()
}
function replace (to) {
history.replace(to)
}
history.listen((location) => {
console.log('請求路由路徑發生變動', location)
})
</script>
</body>
8.react-router基本使用及相關API
----組件
1)<BrowserRouter>
2)<HashRouter>
3)<Route>
4)<Redirect>
5)<Link>
6)<NavLink>
7)<Switch>
----其它
1)history物件
2)match物件
3)withRouter函式
準備:
1)下載react-router: npm install --save react-router@4
2)引入bootstrap.css: <link rel="stylesheet" href="/css/bootstrap.css">
代碼:
----路由組件: views/about.jsx-----
import React from 'react'
export default function About() {
return <div>About組件內容</div>
}
-----路由組件: views/home.jsx------
import React from 'react'
export default function About() {
return <div>Home組件內容</div>
}
------包裝NavLink組件: components/my-nav-link.jsx------
import React from 'react'
import {NavLink} from 'react-router-dom'
export default function MyNavLink(props) {
return <NavLink {...props} activeClassName='activeClass'/>
}
-------應用組件: components/app.jsx------
import React from 'react'
import {Route, Switch, Redirect} from 'react-router-dom'
import MyNavLink from './components/my-nav-link'
import About from './views/about'
import Home from './views/home'
export default class App extends React.Component {
render () {
return (
<div>
<div className="row">
<div className="col-xs-offset-2 col-xs-8">
<div className="page-header">
<h2>React Router Demo</h2>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-2 col-xs-offset-2">
<div className="list-group">
{/*導航路由鏈接*/}
<MyNavLink className="list-group-item" to='/about' >About</MyNavLink>
<MyNavLink className="list-group-item" to='/home'>Home</MyNavLink>
</div>
</div>
<div className="col-xs-6">
<div className="panel">
<div className="panel-body">
{/*可切換的路由組件*/}
<Switch>
<Route path='/about' component={About} />
<Route path='/home' component={Home} />
<Redirect to='/about' />
</Switch>
</div>
</div>
</div>
</div>
</div>
)
}
}
------自定義樣式: index.css------
.activeClass {
color: red !important;
}
------入口JS: index.js------
import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter, HashRouter} from 'react-router-dom'
import App from './components/app'
import './index.css'
ReactDOM.render(
(
<BrowserRouter>
<App />
</BrowserRouter>
/*<HashRouter>
<App />
</HashRouter>*/
),
document.getElementById('root')
)
9. 嵌套路由使用
二級路由組件: views/news.jsx
import React from 'react'
export default class News extends React.Component {
state = {
newsArr: ['news001', 'news002', 'news003']
}
render () {
return (
<div>
<ul>
{
this.state.newsArr.map((news, index) => <li key={index}>{news}</li>)
}
</ul>
</div>
)
}
}
二級路由組件: views/message.jsx
import React from 'react'
import {Link, Route} from 'react-router-dom'
export default class Message extends React.Component {
state = {
messages: []
}
componentDidMount () {
// 模擬發送ajax請求
setTimeout(() => {
const data = [
{id: 1, title: 'Message001'},
{id: 3, title: 'Message003'},
{id: 6, title: 'Message006'},
]
this.setState({
messages: data
})
}, 1000)
}
render () {
const path = this.props.match.path
return (
<div>
<ul>
{
this.state.messages.map((m, index) => {
return (
<li key={index}>
<Link to='???'>{m.title}</Link>
</li>
)
})
}
</ul>
</div>
)
}
}
一級路由組件: views/home.jsx
import React from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
import MyNavLink from './components/my-nav-link'
import News from './views/news'
import Message from './views/message'
export default function Home() {
return (
<div>
<h2>Home組件內容</h2>
<div>
<ul className="nav nav-tabs">
<li>
<MyNavLink to='/home/news'>News</MyNavLink>
</li>
<li>
<MyNavLink to="/home/message">Message</MyNavLink>
</li>
</ul>
<Switch>
<Route path='/home/news' component={News} />
<Route path='/home/message' component={Message} />
<Redirect to='/home/news'/>
</Switch>
</div>
</div>
)
}
10. 向路由組件傳遞引數資料
三級路由組件: views/message-detail.jsx
import React from 'react'
const messageDetails = [
{id: 1, title: 'Message001', content: '戴沐白-朱竹清 幽冥白虎'},
{id: 3, title: 'Message003', content: '奧斯卡-寧榮榮 復活神光'},
{id: 6, title: 'Message006', content: '馬紅俊 白沉香 無'},
]
export default function MessageDetail(props) {
const id = props.match.params.id
const md = messageDetails.find(md => md.id===id*1)
return (
<ul>
<li>ID: {md.id}</li>
<li>TITLE: {md.title}</li>
<li>CONTENT: {md.content}</li>
</ul>
)
}
二級路由組件: views/message.jsx
import React from 'react'
import {Link, Route} from 'react-router-dom'
import MessageDetail from "./views/message-detail"
export default class Message extends React.Component {
state = {
messages: []
}
componentDidMount () {
// 模擬發送ajax請求
setTimeout(() => {
const data = [
{id: 1, title: 'Message001'},
{id: 3, title: 'Message003'},
{id: 6, title: 'Message006'},
]
this.setState({
messages: data
})
}, 1000)
}
render () {
const path = this.props.match.path
return (
<div>
<ul>
{
this.state.messages.map((m, index) => {
return (
<li key={index}>
<Link to={`${path}/${m.id}`}>{m.title}</Link>
</li>
)
})
}
</ul>
<hr/>
<Route path={`${path}/:id`} component={MessageDetail}></Route>
</div>
)
}
}
11.多種路由跳轉方式
二級路由: views/message.jsx
import React from 'react'
import {Link, Route} from 'react-router-dom'
import MessageDetail from "./views/message-detail"
export default class Message extends React.Component {
state = {
messages: []
}
componentDidMount () {
// 模擬發送ajax請求
setTimeout(() => {
const data = [
{id: 1, title: 'Message001'},
{id: 3, title: 'Message003'},
{id: 6, title: 'Message006'},
]
this.setState({
messages: data
})
}, 1000)
}
ShowDetail = (id) => {
this.props.history.push(`/home/message/${id}`)
}
ShowDetail2 = (id) => {
this.props.history.replace(`/home/message/${id}`)
}
back = () => {
this.props.history.goBack()
}
forward = () => {
this.props.history.goForward()
}
render () {
const path = this.props.match.path
return (
<div>
<ul>
{
this.state.messages.map((m, index) => {
return (
<li key={index}>
<Link to={`${path}/${m.id}`}>{m.title}</Link>
<button onClick={() => this.ShowDetail(m.id)}>查看詳情(push)</button>
<button onClick={() => this.ShowDetail2(m.id)}>查看詳情(replace)</button>
</li>
)
})
}
</ul>
<p>
<button onClick={this.back}>回傳</button>
<button onClick={this.forward}>前進</button>
</p>
<hr/>
<Route path={`${path}/:id`} component={MessageDetail}></Route>
</div>
)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/260023.html
標籤:其他
上一篇:python爬蟲--代理的使用
下一篇:Spring Boot入門
