我是新手,reactjs
我有一个小项目reactjs
可以玩和学习。我需要键入将根据URL路径显示的标题类型。因此,以下是我处理路由的index.js:
const history = useRouterHistory(createHistory)({
basename: '/test'
})
class Tj extends React.Component {
render() {
return (
<Router history={history}>
<Route path={"/"} component={Bridge} >
<IndexRoute component={Home} />
<Route path={"user"} component={T} />
<Route path={"home"} component={Home} />
</Route>
<Route path={"/t/"} component={Bridge2} >
<IndexRoute component={T} />
<Route path={"contact"} component={Home} />
</Route>
</Router>
);
}
}
render(
<Provider store={store}>
<Tj/>
</Provider>,
window.document.getElementById('mainContainer'));
如您所见,我将test用作根目录,并根据用户对url的输入,确定应使用哪个标头。这里也是Bridge2.js:
export class Bridge2 extends React.Component {
render() {
return (
<div>
<div className="row">
<Header2/>
</div>
<div className="row">
{this.props.children}
</div>
</div>
);
}
}
和Bridge.js:
export class Bridge extends React.Component {
render() {
// alert(this.props.children.type);
var Content;
if(this.props.children.type){
Content=<div>
<div className="row">
<Header/>
</div>
<div className="row">
{this.props.children}
</div>
</div>;
}
else{
Content=<div>
<div className="row">
<Header/>
</div>
<div className="row">
{this.props.children}
</div>
</div>;
}
return (
Content
);
}
}
当我在webpack开发服务器中运行此程序时,一切正常。例如,当我使用http://localhost:3003/test/
bridge.js加载时,如果我运行http://localhost:3003/test/t/
bridge2.js加载,这是预期的。
但是,由于Web Pack开发服务器不是生产服务器,因此我使用了Tomcat,现在使用了Eclipse Web应用程序项目,并在那儿复制了bundle.js文件和index.html。现在的问题是,当我运行tomcat服务器时,它能够识别并很好地显示此路径:
http://localhost:8080/test/
但是当http://localhost:8080/test/t/
我得到:
HTTP状态404-/ test / t /
基本上说资源文件不可用。据我观察,这在编码中不是问题,因为路由在Web Pack开发服务器中运行良好,但是当涉及到tomcat时,似乎响应路由无法处理它。我的工作有什么问题吗?这样完全可行吗?有人可以帮忙吗?
首先,在使用react-router时,您必须意识到以下差异。
当您在浏览器中输入“ localhost:3003 / test /”时,它将请求服务器,然后它将收到/test/index.html、js包,css,...
之后,每当您单击内部链接(例如'localhost:3003 / test / t /')时,您的浏览器都不会再次请求服务器。
React-router会解析此客户端,重新渲染页面的一部分,并更新浏览器的地址栏(使用html5 pushstate),而不会触发其他服务器请求。
当您直接在地址栏中输入“ localhost:3003 / test / t /”时,浏览器将请求服务器,而Tomcat没有/test/t/index.html左右,并且它返回404。这是因为Tomcat对react-redux和javascript都不了解。
解决此问题的一种方法是将404错误配置为转发到/test/index.html。这可能是您的webpack开发服务器默认配置的方式。
如果您的Tomcat前面有一个,则有很多在apache上执行此操作的示例。搜索“ html5 pushstate apache config”。
这是一个例子
httpd.conf
...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
...
如果仅使用tomcat,则可以尝试在war文件中的web.xml中指定它。
...
<error-page>
<error-code>404</error-code>
<location>/index.html</location>
</error-page>
...
请注意,这不是特定于react-route的问题,每个使用html5 pushstate的应用都需要以某种方式进行处理。Javascript服务器可以更无缝地处理此问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句