java - Spring引导控制器映射到反应组件
问题描述
我正在使用我的反应应用程序中切换路线 -
<Route path="/myBootDomain" render={props => {
//check route path
const onpathA = window.location.href.indexOf('/pathA') !== -1;
const onpathB = window.location.href.indexOf('/pathB') !== -1;
if (onpathA){ return <PathAComponent />;}
else if(onpathB){ return <onpathBComponent />;}
}}/>
当我在本地主机上运行应用程序时,它按预期工作,所以我希望我的控制器将子域映射到正确的路由,例如控制器 -
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/pathA")
public class WebContentController {
@RequestMapping(method = RequestMethod.GET)
public void method(HttpServletRequest request, HttpServletResponse httpServletResponse) {
httpServletResponse.setHeader("Location", "/myBootDomain/pathA");
httpServletResponse.setStatus(302);
}
}
当尝试访问http://localhost:8080/myBootDomain/pathA而不是重定向到索引文件时,我被重定向到同一个控制器(无限循环)。
我的 index.html 在/resources/static
.
感谢您的帮助。
解决方案
React 使用路由的方式与您之前使用服务器端框架(如 JSF、PrimeFaces 和其他类似框架)的方式不同。
通常在 React 中,所有路由都在客户端处理(至少应该以这种方式完成),这种方法称为单页应用程序,因为您有一个页面,其中组件将根据您在客户端的路由和那些组件与服务器通信并根据与服务器一起传递的响应更改其内容。<Route>
在这里,当路径更改为 /pathA 时,您将在客户端和浏览器中使用 Component 处理您的路由,PathAComponent
在这种情况下,将呈现并且不会向服务器发送任何请求,因为 React 控制着这里的一切)。您应该以这样的方式设计您的 PathAComponent,当它被渲染时,它会在后端使用 Http Rest 调用调用您的方法,并根据响应执行某些操作(例如向用户显示响应的状态代码)。
检查此链接以进行进一步讨论
,下面显示了执行您想做的事情的更清晰的方法:
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route path='/pathA' exact={true} component={PathAComponent}/>
<Route path='/pathB' exact={true} component={PathBComponent}/>
</Switch>
</Router>
)
}
}
此处,当客户端PathAComponen
t 中路径更改为 /pathA 时,将呈现路径更改为 /pathB 组件PathBComponent
时。到目前为止,没有请求发送到服务器与服务器通信,您应该直接在您的PathAComponent
and中调用您的 REST api PathBComponent
,通常在组件的 componentDidMount 方法中。
class PathAComponent extends Component {
constructor(props) {
super(props);
this.state = {status: false, isLoading: true};
}
componentDidMount() {
this.setState({isLoading: true});
fetch('/myBootDomain/pathA')
.then(response => this.setState({status: response.status, isLoading: false}));
}
render() {
return (
<div>
statusCode: {status}
</div>
);
}
}
推荐阅读
- ios - AWS Device Farm - 测试卡在登录页面
- sql-server - TSQL - 数据库之间的数据传递
- java - 如何将用户输入(使用扫描仪)集成到 while 循环中以计算 1+2+3+....n,其中 n 是任何正整数?
- unity3d - Unity Shader Graph:如何从时间节点加快时间?
- android - 处理 JobIntentService 和线程休眠
- java - 使用 IntelliJ IDEA 在 Java 类中搜索错误的记录器定义
- java - appium 驱动程序在 URL 中显示错误
- java - java.net.ProtocolException:服务器重定向太多次
- haskell - 从 Haskell 中的数据类型中提取字段
- bash - ANSI C 引号被添加到我的 bash 代码中