首页 > 解决方案 > 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.

感谢您的帮助。

标签: javareactjsspring-bootreact-router

解决方案


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>
            )
         }
}

此处,当客户端PathAComponent 中路径更改为 /pathA 时,将呈现路径更改为 /pathB 组件PathBComponent时。到目前为止,没有请求发送到服务器与服务器通信,您应该直接在您的PathAComponentand中调用您的 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>
            );
      }
}

推荐阅读