我这些天一直在努力学习React和React-router,我迷失了。我已经阅读了很多关于如何使用react-router,阅读所有文档的内容,但我还无法连接这些内容。 我试图设置一个包含Home,Login和About页面的网站,应该有一个父navBar。我有一台运行快递的服务器,我希望能够在用户登录时更改主页内容。 我现在正在提供静态文件,所以应该有一个index.html,about.html和login.html?我已尝试使用服务器端渲染(不确定它是否是正确的方法),但所有教程都已过时且文档似乎连接不好。
我知道应该有一个App.js文件,一个routes.js和一个client-side.js。这就是我所拥有的:
App.js
var React = require('react');
var socket = require("socket.io-client")("http://localhost:3000");
var Login = require('./Login');
var NavBar = require('./NavigationBar');
var About = require('./About');
module.exports = React.createClass({
render: function(){
return (
<div>
<NavBar />
<Login /> --> I should put something related to routing here? The right component for the url the user typed?
</div>
);
},
});
客户side.js
var React = require('react');
var ReactDOM = require('react-dom');
var App = require('./react/App');
ReactDOM.render(<App />, document.getElementById("react-container"));
APP-server.js
var express = require("express");
var http = require('http');
var app = express();
var server = http.createServer(app).listen(3000);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname + "/public"));
console.log("Server listening on http://localhost:3000");
io.on('connection', function(socket){
console.log("Connected to Socket.io with id: %s", socket.id);
});
module.exports = server;
我已经尝试了很多东西,但它可能很难......我只想拥有一台路由器,并且能够访问用户尝试访问的页面服务器......
答案 0 :(得分:2)
找到解决方案:
app-server.js:添加了这个
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
});
routes.js:已添加
import React from 'react';
import { IndexRoute, Router, Route, browserHistory } from 'react-router';
import { createHistory, useBasename } from 'history'
import App from './App';
import Login from './Login';
import About from './About';
//Removes /#/k_adarwf
const history = useBasename(createHistory)({
basename: '/'
});
module.exports = (<Router history={history} >
<Route path="/" component={App}>
<IndexRoute component={Login} />
<Route path="about" component={About} />
</Route>
</Router>);
App.js:已更改为
module.exports = React.createClass({
render: function(){
return (
<div>
<NavBar />
{this.props.children}
</div>
);
},
});