【问题标题】:ReactRouter and react-create-app; how to render subcomponents by id?反应路由器和反应创建应用程序;如何按 id 渲染子组件?
【发布时间】:2018-01-19 09:39:28
【问题描述】:

我正在尝试了解如何在当前项目中正确使用 ReactRouter。该项目包含一个带有概览的仪表板,并且可以打开每个项目进行编辑。我正在尝试在用户单击链接后导航到特定项目并呈现编辑视图。

index.js:

ReactDOM.render(
  <Router>
    <div>
      <Route exact path="/" component={App}/>
      <Route exact path="/dashboard" component={App}/>
      <Route path="dashboard/:id" component={Editing}/>
      <Route exact path="/about" component={About}/>
    </div>
  </Router>, document.getElementById('root'));

App 组件包含一个容器

import ItemContainer from './components/ItemContainer.js';
...
<div className='container'>
     <ItemContainer user={this.state.user} items={this.state.items} userProfile={this.state.userProfile}/>
</div>

容器根据容器的状态将项目列表映射到仪表板。

if(this.state.view === "editing"){
      return (
         <ItemEdit item={this.state.currentItem} uid={this.props.user.uid} 
         viewList={this.changeViewList.bind(this)}/>
      )}
if(this.state.view === "list"){
      return (
      this.props.items.map (item =>
            <li key={item.id}>
                <Item item={item} user={this.props.user} view={this.changeViewEditing.bind(this)}/>
            </li>
      ))}

每个项目都从项目组件呈现,其中包含一个用于更改到编辑视图的按钮

<div>
    <h3>
        {this.props.appName}
    </h3>
    <Link to={`/dashboard/${this.props.item.id}`}><button onClick={() => this.editItem(this.props.item)}>Edit</button></Link>
</div>

在最后一个块中,问题当然是链接导致空url dashboard/item:id。从示例中我一直试图了解如何准确配置它,因为编辑视图只是 App 组件的子组件。我已经尝试过 ReactRouter 网站上的示例,但我无法理解如何在我的上下文中实现他们的示例。

谢谢!

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    &lt;Route path="/dashboard/:id" component={Editing}/&gt; - 试试这个,也许有帮助

    / - 可能你错过了这个符号

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题。虽然对我来说只需要 5 个组件,所以我使用了一个开关盒,但你可以理解基本原理。

      class TestComponent implements Component{
         constructor(props){
            super(props);
         }
           renderComponent(){
      
              switch(this.props.params.Id){
                 case 1: return (<Component1/>); 
                         break;
                 case 2: return (<Component2/>); 
                          break;
                 case 3: return (<Component3/>); 
                          break;
                 default: return(<div></div>);
                          break;
      
             }
           }
             render(){
                return(<div>{this.renderComponent()}</div>);
            }
      }
      

      【讨论】:

      • 嘿,谢谢!我想我可能应该更改交换机结构,但这能解决路由器问题吗?我可能在这里遗漏了一些东西;主要问题是当我在编辑视图中渲染 App>Container>Item:id 时,页面是空白的,因为 index.js 中的路由器不知道要渲染什么。我的目标是它会呈现应用程序,其编辑状态指向 /dashboard/id:3243414
      • 如果您有单独的 url 而不是 Id,则 switch 可以工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2017-12-23
      • 2018-07-26
      • 2020-01-08
      • 2023-04-03
      • 2018-06-02
      • 2021-04-24
      相关资源
      最近更新 更多