一次react从0开始建站体验及各种填坑--开发中遇到的各种问题

接上文:一次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 (
            
                
                    
                    
                
            
        )
    }
}

src/pages/Homepage/index.js 代码如下

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

export default class Homepage extends Component {

    //...
    
    render() {
        return(
            
链接到Aboutus
) } }

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(
            
... { this.state.isLoading?
正在载入…
:
加载更多
} ...
) } }

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 (
            
                
                    
                    
                    ...
                    
                
            
        )
    }
}

你可能感兴趣的:(react.js)