create-react-app与react-router

4月份的一篇博客,去重之后,主要介绍create-react-app与react-router

create-react-app

基本使用

原文

  • 安装
    yarn add create-react-app

  • 创建ts版的react项目
    npx create-react-app [app] –scripts-version=react-scripts-ts

  • 启动
    yarn start

  • 自定义配置
    yarn eject

deploy

原文

  • Static Server
    Serve
    Tomcat
    Nginx [*]

    注意相对路径,可以在package.json中配置"homepage": "http://mywebsite.com/relativepath",

    也可以在react-router中使用basename来设置

  • Dynamic Server
    Express [*]
    Webship

    注意路径的差异,/todos/42 => /build/todos/42

react-router

原文

前端渲染

大约是靠Route来注册,靠Link来导航各个路由

  • Router
    At the core of every React Router application should be a router component
    Generally speaking, you should use a if you have a server that responds to requests and a if you are using a static file server.

  • Route Match
    大约是靠Route来注册,与服务器端相同,没有key值的总是会渲染
    注册还有Switch,可以当成Router的分组,在这个组里只会选择第一个匹配的Route

  • Navigation
    靠Link来导航各个路由
    NavLink是一种特殊的Link,他能自动active
    Redirect是一种强制的force navigation

  • 示例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    function App() {
    return (
    <Router>
    <div>
    <Header />

    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    </div>
    </Router>
    );
    }

    function Home() {
    return <h2>Home</h2>;
    }

    function About() {
    return <h2>About</h2>;
    }

    function Header() {
    return (
    <ul>
    <li>
    <Link to="/">Home</Link>
    </li>
    <li>
    <Link to="/about">About</Link>
    </li>
    </ul>
    );
    }

后端渲染

react可以做后端的渲染,使用的是ReactDomServer来做
首先它使用的是StaticRouter,而不是BrowserRouter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//client
<BrowserRouter>
<App/>
</BrowserRouter>

// server (not the complete story)
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>

const context = {};
const markup = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);

if (context.url) {
// Somewhere a `<Redirect>` was rendered
redirect(301, context.url);
} else {
// we're good, send the response
}