react-router4 第一篇

时间:2022-01-22 15:08:32

无奈,英语4级没过,只能靠猜了。。

首先就是安装了

npm install --save-dev react
npm install --save-dev react-dom
npm install --save-dev react-router@4
npm install --save-dev react-router-dom

不管有用没用先装上!!!

新建一个webpack.config.js,这里使用webpack2来打包jsx

var webpack = require("webpack");
var path = require("path"); module.exports = {
context: __dirname + "/app/js",
entry: {
login: ["./login.js"], // 为了将来的多入口写法
},
devtool: "source-map", // 为了可以在控制台跟踪到自己的代码位置,精确到行
output: {
path: path.resolve(__dirname,"static/js"), // 输出目录
filename: "[name].bundle.js", // 输出文件名
},
module: {
rules: [
{
test: /\.js|\.jsx/,
exclude: /node_modules/,
use: [{
loader: "babel-loader",
options: {
presets: ["es2015", "react", "babel-polyfill"] // 打包模块,babel-polyfill是为了让axios兼容ie的,,不用promise对象可以不写
}
}]
},
{
test: /\.css$/,
use: [
{
loader: "style-loader",
options: {
// modules: true // 设置css模块化,详情参考https://github.com/css-modules/css-modules
}
},
{
loader: "css-loader",
options: {
// modules: true // 设置css模块化,详情参考https://github.com/css-modules/css-modules
}
},
// {
// loader: "postcss-loader", // 添加浏览器前缀
// options: {
// plugins: function () {
// return [
// require('autoprefixer')
// ]
// }
// }
// }
]
}
]
},
devServer: { // 打包加自动刷新,webpack-dev-server --hot 可以自动热替换,,,虽然我并没有感觉到有多快。。。
contentBase: __dirname,
host: '0.0.0.0',
port: 5005,
inline: true,
historyApiFallback: true,
}
}

开始写react-router啦

以下代码,完全复制于 https://reacttraining.com/react-router/web/example/basic

import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom' const BasicExample = () => (
<Router> // 创建一个路由
<div>
<ul> // Link 组件 相当于a标签,to属性相当于a标签中的href,可以打开控制台看到,
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul> <hr/>
// 监听路由,地址栏的变化,,很抱歉exact的意思我现在都不知道,观察到exact 在跟路由下,和exact={activeOnlyWhenExact}
<Route exact path="/" component={Home}/> // 如果地址栏访问了跟路径,比如http://localhost:5005/ 就会去渲染<Home /> 组件
<Route path="/about" component={About}/> // 如果地址栏访问了/about 路径,比如http://localhost:5005/about 就会去渲染<About/> 组件
<Route path="/topics" component={Topics}/> // 如果地址栏访问了topics 路径,比如http://localhost:5005/topics 就会去渲染<Topics/> 组件
</div>
</Router>
)

这就是react-router的最简单的用法,什么附加功能都没有,,仅仅是根据地址栏去渲染相应的组件!!!,,仅此而已,

不过这里有一个特别坑的地方,如果你的当前路径是http://localhost:5005/templates/的话,去访问 /about 路由,地址栏会直接变成http://localhost:5005/about,,然后再也后退不回去了,,当然后面的教程里肯定有解决方法,只是我还不知道,。。

以上代码,完全复制于 https://reacttraining.com/react-router/web/example/basic