簡體   English   中英

使用React Router進行簡單導航[錯了]

[英]Simple navigation with react router [gone wrong]

我開始研究我的工程論文,並決定在React中將其編寫為SPA,並與ASP.NET Core后端上的REST API進行通信。 到目前為止,我已經使用ASP.NET MVC和Winforms完成了一些應用程序,但是我想擴展我的知識並學習一些新技術。 因此,我最近開始學習React,一開始我試圖在其中創建非常簡單的SPA。

這是問題所在:假設我們有一個包含大學數據的應用程序。 即:大學,其系,系的學科,學科的講師等。

我想對上述結構進行簡單的導航-在主頁上顯示我在數據庫中擁有的每所大學,然后我希望能夠單擊大學並獲取其系,然后在系列表中單擊一個部門,然后從該部門獲取例如主題,依此類推,您就知道了。

我的具有必要端點的后端正在localhost上運行。 問題在於何時何地在前端獲取數據,如何在組件之間傳遞id,如何為此類應用程序構造結構等。

我花了3天的時間進行嘗試,但不幸的是沒有任何效果,但是現在我的腦海一片混亂,我考慮重新使用舊的ASP.NET MVC。。但是我敢肯定,肯定有一些東西我很想念我,因為我不相信這是不可能的。.我想我也可能有很多MVC習慣,可能會影響我對Web api和純前端應用程序的理解。

我已經閱讀了官方文檔,觀看了教程,stackoverflowed,嘗試了自己的想法,每步重復5次。 簡單的路由和整體反應工作流程對我來說不是問題,問題在於特定的情況。

誰能為我提供一些信息或線索,以了解如何在React中處理此類設計(理想情況下帶有示例)?


編輯

好的,我現在分享我今天想出的設計。 這可以按預期工作,但是無法通過在瀏覽器的搜索框中輸入特定的路線來手動進行選擇-唯一的方法是沿着整個“大學路徑”瀏覽

App.js

const App = () =>
  <BrowserRouter>
    <>
      <NavBar />

      <div className="row home-container">
        <div className="col s12 m8 l9 home-part">
          <div className="data-container">
            <Route path="/" component={MainContainer} />
          </div>
        </div>
        <Sidebar />
      </div>
    </>
</BrowserRouter>

export default App

MainContainer.js

const defaultBreadcrumb = { title: "Uczelnie", path: "/universities" };

class MainContainer extends React.Component {
  state = {
    elements: [],
    breadcrumbs: [
      defaultBreadcrumb
    ]
  }

  componentDidMount() {
    fetch(`https://localhost:44349/api/v1/universities`)
      .then(res => res.json())
      .then(json => this.setState({elements: json}));
  }

  componentWillReceiveProps(nextProps){
    if(nextProps){
      var newBreadcrumbs = nextProps.location.breadcrumbs ? nextProps.location.breadcrumbs : [defaultBreadcrumb];

      this.setState({
        breadcrumbs: newBreadcrumbs
      });
    }
  }

  render() {
    return (
      <>
        <nav className="colornav">
          <div className="nav-wrapper path-header-wrapper">
            <div className="col s12 subsite-title">
              {this.state.breadcrumbs.map((b, key) => (
                <NavLink key={key} to={b.path} className="breadcrumb">{b.title}</NavLink>
              ))}
            </div>
          </div>
        </nav>

        <div className="home-content">
          <ul className="collection">
            <Route 
              exact 
              path="/universities" 
              render={() => {return <Universities elements={this.state.elements} />}} 
            />
            <Route 
              exact 
              path="/universities/:id"
              render={() => { return <Departments {...this.props} />}} 
            />
            <Route 
              exact 
              path="/universities/:id/Lessons"
              render={() => { return <Lessons {...this.props} />}} 
            />
          </ul>
        </div>
      </>
    );
  }
}

export default MainContainer

Universities.js

const Universities = ({elements}) => 
  <>
    {elements.map((u) => 
      <NavLink 
        key={u.name} 
        to={{
          pathname: `/universities/${u.name}`, 
          univId: u.universityId,
          univName: u.name,
          breadcrumbs: [
            {title: "Uczelnie", path: `/universities`}, 
            {title: u.name, path: `/universities/${u.universityId}`}
          ]
        }} 
        className="collection-item path-list-item">

        <div>{u.name}
          <li className="secondary-content">
            <i className="material-icons">send</i>
          </li>
        </div>
      </NavLink>
    )}
  </>

export default Universities

Departments.js

class Departments extends React.Component {
  state = {
    elements: []
  }

  componentDidMount() {
    fetch(`https://localhost:44349/api/v1/departmentsofuniversity/${this.props.location.univId}`)
      .then(res => res.json())
      .then(json => this.setState({elements: json}));
  }

  render() {
    return (
      <>
        {this.state.elements.map((d) => 
          <NavLink 
            key={d.name} 
            to={{
              pathname: `/universities/${d.name}/lessons`, 
              deptId: d.departmentId,
              deptName: d.name,
              breadcrumbs: [
                {title: "Uczelnie", path: `/universities`}, 
                {title: this.props.location.univName, path: `/universities/${this.props.location.univId}`}, 
                {title: d.name, path: `/universities/${this.props.location.univId}/lessons`}
              ]
            }} 
            className="collection-item path-list-item">

            <div>{d.name}
              <li className="secondary-content">
                <i className="material-icons">send</i>
              </li>
            </div>
          </NavLink>
        )}
      </>
    );
  }
}

export default Departments

最后-Lessons.js

class Lessons extends React.Component {
  state = {
    elements: []
  }

  componentDidMount() {
    fetch(`https://localhost:44349/api/v1/lessonsfromdepartment/${this.props.location.deptId}`)
      .then(res => res.json())
      .then(json => this.setState({elements: json}));
  }

  render() {
    return (
      <>
        {this.state.elements.map((l, key) => 
          <NavLink 
            key={key} 
            to={{
              pathname: `/universities/${l.name}/Lessons/${l.name}`, 
              deptId: l.departmentId,
              breadcrumbs: [
                {title: "Uczelnie", path: `/universities`}, 
                {title: this.props.location.univName, path: `/universities/${this.props.location.univId}`}, 
                {title: this.props.location.deptName, path: `/universities/${this.props.location.deptName}/lessons`},
                {title: l.name, path: `/universities/${this.props.location.deptId}/lessons/${l.name}`}
              ]
            }} 
            className="collection-item path-list-item">

            <div>{l.name}
              <li className="secondary-content">
                <i className="material-icons">send</i>
              </li>
            </div>
          </NavLink>
        )}
      </>
    );
  }
}

export default Lessons

由於所有這些都是非常重復的,當我們開始更深入地研究大學時,我認為最好將這些列表放到一個List組件中(如果要顯示更多內容,可以包含一些特定屬性),並且只通過獲取元素。 幾乎整個應用程序都使用該“類似於列表”的gui,因此它可能很有用。 我現在就是這種情況。

現在,當您看到什么設計時,我便可以隨意分享您的想法。 也許我應該以其他更好的方式完成它?


編輯2

更新了代碼,添加了面包屑! 很酷,但是我前面提到了一個大問題-我無法直接轉到特定的路線,因此無法從課程回到部門...所以整個Router事情都是無用的,尤其是當我想共享時鏈接到特定的路線(將來)。 無論如何,這里是一個更新的代碼。

問題在於何時何地在前端獲取數據,如何在組件之間傳遞id,如何為此類應用程序構造結構等。

通常,您將為此使用狀態容器庫。 最常用於React的是Redux 您將在存儲中存儲/緩存響應數據,使用操作激發請求並在化簡器中解析響應。 您還可以使用redux-promise中間件為異步調用/請求調度操作。

一個很好的視頻教程可以對此進行深入解釋, 網址為: https : //www.udemy.com/react-redux/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM