【问题标题】:Can't get Params from id routes无法从 id 路由中获取参数
【发布时间】:2018-05-05 21:30:54
【问题描述】:

我的项目遇到了一个问题。我正在尝试展示一个组件并使用 this.props.match.params,但无论我做什么,我都无法定义。

路线:

const App = () => (
    <BrowserRouter>
        <Fragment>
            <Header/>
            <main>
                <Switch>
                    <Route path="/show/:id" component={Show}/>
                    <Route path="/" component={Home}/>
                </Switch>
            </main>
        </Fragment>
    </BrowserRouter>
);

export default App;

那么我的家乡路线上有一个处理程序:

async handleSubmit(searchId) {
    const id = await DwellingService.findSiocId(searchId);
    if (id) {
        this.props.history.push(`/show/${id}`);
    }
}

最后在我的展示组件上

   componentDidMount() {
            console.log(this.props.match.params)
            const {id} = this.props.match.params;
            if (id) {
                this.props.requestFindDwelling(id);
            }
        }

所以我一直在研究,我认为这不是反应路由器问题,首先当我尝试通过键入路由来访问路由时,我在 bundle.js 上遇到了意外 > 解决了在索引上添加 &lt;base href="/" /&gt; 的问题。 html。 现在我的组件通过显示组件的 console.log 渲染正常,给了我这个:

isExact:false
params:{}
path:"/show"
url:"/show"

当我启动项目以便能够使用浏览器历史记录并且通过刷新页面不会出错时,我必须将其添加到我的索引文件中:

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, './public/index.html'), function(err) {
        if (err) {
            res.status(500).send(err);
        }
    });
});

对于我得到的那种错误,我假设找不到路由并将我重定向到 /show。

【问题讨论】:

    标签: reactjs react-router history


    【解决方案1】:
    <Switch>
        <Route path="/show/:id" component={Show}/>
        <Route path="/" component={Home}/>
    </Switch>
    

    这将永远不会渲染Home,因为Switch 会渲染第一个匹配的东西,而/ 将始终匹配第一个路由。不确定这是否能解决问题,但请尝试让我知道:

    <Switch>
        <Route exact path="/" component={Home}/> // exact is important
        <Route path="/show/:id" component={Show}/>
    </Switch>
    

    【讨论】:

    • 这解决了它,这是一个顺序问题,我花了几个小时试图修复它哈哈简单甚至不需要确切的
    猜你喜欢
    • 1970-01-01
    • 2020-01-04
    • 2019-08-11
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    相关资源
    最近更新 更多