接上文:一次react从0开始建站体验及各种填坑--开始前的准备
这里记录一些实际开发中遇到的一些问题的解决方法,大量代码预警
1、多页面及链接
假设有两个页面,分别是Homepage和Aboutus,Homepage是首页,建立目录和文件:src/pages/Homepage/index.js、src/pages/Aboutus/index.js
修改 src/App.js
import React, { Component } from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Homepage from './pages/Homepage';
import Aboutus from './pages/Aboutus';
export default class App extends Component {
render() {
return (
<Router history={createBrowserHistory()}>
<Switch>
<Route extra path="/" component={Homepage} />
<Route extra path="/Aboutus" component={Aboutus} />
</Switch>
</Router>
)
}
}
src/pages/Homepage/index.js 代码如下
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class Homepage extends Component {
//...
render() {
return(
<div>
<Link to="/Aboutus">链接到Aboutus</Link>
</div>
)
}
}
2、上拉加载更多
import React, { Component } from 'react';
let timeoutId
export default class Homepage extends Component {
state = {
isLoading: false
}
componentDidMount() {
window.addEventListener('scroll', this.bindLoadMore)
//监听浏览器滚动
}
componentWillUnmount() {
window.removeEventListener('scroll', this.bindLoadMore)
//离开页面后取消监听浏览器滚动
}
bindLoadMore = () => {
if (!this.state.isLoading) {
if (timeoutId) clearTimeout(timeoutId)
timeoutId = setTimeout(this.loadMore, 50)
}
}
loadMore = () => {
const loadMore = this.refs.loadMore
if(loadMore){
const top = loadMore.getBoundingClientRect().top,
windowHeight = window.screen.height
if (top && top < windowHeight) {
this.loadData()
}
}
}
loadData = () => {
//...
//加载数据
}
//...
render() {
return(
<div>
...
{
this.state.isLoading?
<div>正在载入…</div>
:
<div ref="loadMore" onClick={this.loadData}>加载更多</div>
}
...
</div>
)
}
}
3、判断是否为移动端
var isMob=/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)?true:false;
4、设置404页面
建立目录和文件:src/pages/Page404/index.js,在src/App.js中增加
...
import Page404 from './pages/Page404';
...
export default class App extends Component {
render() {
return (
<Router history={createBrowserHistory()}>
<Switch>
<Route extra path="/" component={Homepage} />
<Route extra path="/Aboutus" component={Aboutus} />
...
<Route exact path="*" component={Page404} />
</Switch>
</Router>
)
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。