React单页应用SPA

Posted huangtonghui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React单页应用SPA相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React-SPA</title>
    <script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
    <script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
    <script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<script type="text/babel">
    const About = React.createClass({
        render() {
            return <h3>About</h3>
        }
    });

    const Inbox = React.createClass({
        render() {
            return (
                <div>
                    <h2>Inbox</h2>
                </div>
            )
        }
    });

    const Home = React.createClass({
        render() {
            return <h3>Home</h3>
        }
    });

    const App = React.createClass({
        getInitialState() {
            return {
                route: window.location.hash.substr(1)
            }
        },

        componentDidMount() {
            window.addEventListener(‘hashchange‘, () => {
                this.setState({
                    route: window.location.hash.substr(1)
                })
            })
        },

        render() {
            let View;
            switch (this.state.route) {
                case ‘/about‘: View = About; break;
                case ‘/inbox‘: View = Inbox; break;
                default:      View = Home;
            }

            return (
                    <div>
                        <h1><a href="#/">Home</a></h1>
                        <ul>
                            <li><a href="#/about">About</a></li>
                            <li><a href="#/inbox">Inbox</a></li>
                        </ul>
                        <View/>
                    </div>
            )
        }
    });

    ReactDOM.render(<App />, document.body);
</script>
</body>
</html>

  

以上是关于React单页应用SPA的主要内容,如果未能解决你的问题,请参考以下文章

前端单页应用微服务化解决方案2 - Single-SPA

single-spa原理

单页应用SPA做SEO的一种清奇的方案

单页应用程序路由

SPA单页应用

单页应用SPA开发最佳实践