【问题标题】:React router catching webapi routesReact 路由器缓存 web api 路由
【发布时间】:2020-06-01 12:01:54
【问题描述】:

.NET Core 3.1 Web 应用程序,带有 React 16.12.0。

问题

React 新手...当我获取 'api/checksheet/types' 时,它会被 '/checksheet/:checkSheetTypeId' 捕获,并尝试加载为该路由声明的组件。

如何消除前端和服务器端路由的冲突?

服务器端,2 个端点

[Route("api/[controller]")]
[ApiController]
public class CheckSheetController : ControllerBase
{
    // GET: api/checksheet/types
    [HttpGet]
    public IList Types()
    {
    }

    // GET: api/checksheet/{id}
    [HttpGet("{id}")]
    public Dto Get(int id)
    {
    }
}

App.js

<Layout>
    <Switch>
        <Route exact path='/checksheet/add' component={AddChecksheet} />
        <Route path='/checksheet/:checkSheetTypeId' component={TasksPage} />
    </Switch>
</Layout>

组件

import React, { Component } from 'react';

export class NavMenu extends Component {
    constructor(props) {
        super(props);
        this.state = { types: [], loading: true };
    }

    componentDidMount() {
        this.getTypes();
    }

    async getTypes() {
        const response = await fetch('api/checksheet/types');
        const data = await response.json();
        this.setState({ types: data, loading: false });
    }
}

【问题讨论】:

    标签: .net reactjs .net-core react-router asp.net-core-webapi


    【解决方案1】:

    考虑一下,我可以通过遵循 RESTful API 命名约定来解决这个问题,以便 CheckSheetController 是复数形式,然后让我的端点调用 /api/checksheets/{id}

    虽然必须有其他解决方案....

    【讨论】:

      猜你喜欢
      • 2017-03-24
      • 2015-05-04
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多