问题描述:我在Routes.js里把 '/'路由的exact属性注释后,感觉所以 / 一下的都会走Home,/ttt的Login则不会渲染,而且点击Login的Link后,也会把Home一起渲染。
我检测了client和server端的代码,都没找到问题,而且我也对比了老师5-8,5-9,5-10的代码也没发现什么,视频也重复看了几遍,还是不行。请老师帮忙解答一下
client/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route } from 'react-router-dom'
import routes from '../Routes'
import { Provider } from 'react-redux'
import getStore from '../store'
const App = () => {
return (
<Provider store={getStore()}>
<BrowserRouter>
<div>
{routes.map((route) => <Route {...route} />)}
</div>
</BrowserRouter>
</Provider>
)
}
ReactDOM.hydrate(<App />, document.getElementById('root'));
server/index.js
import express from 'express'
import { render} from './util'
const app = express();
app.use(express.static('public'))
app.get('*', function (req, res) {
res.send(render(req));
});
const server = app.listen(3000);
server/util.js
import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter, Route, matchPath } from 'react-router-dom'
// import { matchRoutes } from 'react-router-config'
import routes from '../Routes'
import { Provider } from 'react-redux'
import getStore from '../store'
export const render = (req) => {
const store = getStore()
// const matchedRoutes = matchRoutes(routes, req.path)
const matchRoutes = []
// 根据路由的路径,来往store里面加数据
routes.some(route => {
const match = matchPath(req.path, route)
if (match) {
matchRoutes.push(route)
}
})
console.log(matchRoutes)
const content = renderToString(
<Provider store={store}>
<StaticRouter context={{}} location={req.path}>
<div>
// 这里的matchRoutes,我也改成routes,效果一样
{matchRoutes.map((route) => (<Route {...route} />))}
</div>
</StaticRouter>
</Provider>
);
return (
`
<html>
<head>
<title>ss</title>
</head>
<body>
<div id="root">${content}</div>
<script src='/index.js'></script>
</body>
</html>
`
)
}
Routes.js
import Home from './containers/Home'
import Login from './containers/Login'
export default [
{
path: '/',
component: Home,
// exact: true,
loadData: Home.loadData,
key: 'home',
routes: [
{
path: '/ttt',
component: Login,
exact: true,
key: 'ttt',
},
],
},
{
path: '/login',
component: Login,
exact: true,
key: 'login',
},
]
package.json
"dependencies": {
"@babel/preset-react": "^7.0.0",
"axios": "^0.18.0",
"babel-preset-stage-0": "^6.24.1",
"express": "^4.16.4",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"react-router-config": "^4.4.0-beta.6",
"react-router-dom": "^4.3.1",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"webpack-merge": "^4.1.5",
"webpack-node-externals": "^1.7.2"
},
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.2.3",
"babel-loader": "^8.0.4",
"webpack": "^4.28.3",
"webpack-cli": "^3.1.2"
}