【问题标题】:React pass an object to the routeReact 将对象传递给路由
【发布时间】:2019-12-15 11:20:50
【问题描述】:

我在“app.js”文件中设置了我的应用程序我在渲染方法中定义了我的路由器

        <HashRouter>
            <StatusToast />
            <Switch>
                <Route
                    exact={true}
                    path="/"
                    render={props => (
                        <ImageScene{...props} title="Images & Information Search" />
                    )}
                />
                <Route path="/case/:id/images" component={DetailsScene} />
            </Switch>
        </HashRouter>

ImageScene 对表格行单击,我调用这样的方法: this.props.history.push(/case/${id}/images)

这会触发一个路由并加载DetailsScene,我可以在其中获取传入的id,就像这样this.props.match.params.id,到目前为止所有工作都没有任何问题。

我的问题是如何传递一个超过字符串(id)的字符串,我能否以某种方式将整个对象传递给路由?

我尝试为第二条路线做这样的事情,而不是: &lt;Route path="/case/:id/images" component={DetailsScene} /&gt;

要在ImageScene 上设置一个可以公开选择对象的方法,现在让我们做一个简单的方法,例如:

export function getSelectedRow() {
   return {
      title: 'test'
   }
}

然后设置如下路线:

const object = getSelectedRow();

<Route path="/case/:id/images" 
       render={props => (<DetailsScene{...props} title={object.title} />
       )} 
/>

但我无法让它工作......任何帮助都会很好,我对反应和整个路由器都是全新的。

【问题讨论】:

    标签: reactjs react-router-dom


    【解决方案1】:

    您可以向 history.push (https://reacttraining.com/react-router/web/api/history) 添加状态,该状态可用于正在渲染的组件 (DetailsS​​cene)。请记住使用Router(...) 包装 DetailsS​​cene 以在其 props 中提供 history.location.state。

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 2015-10-30
      • 2019-08-27
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多