使用路径参数的React Router不起作用

时间:2019-05-27 06:24:51

标签: reactjs react-router react-router-v4

我有一个具有以下配置的React BrowserRouter。

<BrowserRouter>
        <div>
            <Switch>
                <Route path={`/`} component={Home} exact/>
                <Route path={`/about`} render={(props) => <About {...props}/>} exact/>
                <Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
            </Switch>
        </div>

在“关于页面”中,有带有以下标签的产品。如果我单击链接,则URL会更改,并且“产品”页面会正确显示。

<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>

但是,当我使用确切的网址直接进入“产品”页面时。渲染将无法正常工作。

 e.g localhost:3000/products/123/books

你知道是什么原因引起的吗?

5 个答案:

答案 0 :(得分:0)

我相信您的问题是,在您直接访问网址时会收到无法获取的错误消息。尝试在webpack.config.js

中设置historyApiFallback: true

答案 1 :(得分:0)

在您的产品组件中使用

如果组件是全状态组件 this.props.match.params.id for id = 123 this.props.match.params.slug for slug = books

如果组件是无状态组件 那么您需要使用“ withRouter”使以上行可用 从“反应路由器”导入{withRouter};

并使用此方法包装函数

const MyComponent =()=> {} 使用Router(MyComponent)导出默认值

应该可以!!!

答案 2 :(得分:0)

要通过任何网址运行“客户端虚拟”路由,您需要服务器端支持-f.e. apache mod-rewrite。

已经被here插入

答案 3 :(得分:0)

根据您的输入,我想说这是语法错误或组件中componentDidMount / useEffect的问题。

我想我虽然发现语法错误:“ product.slug>”

您应该在弹ug之后删除“>”,这样可能会很好!

答案 4 :(得分:0)

据我了解这段代码:

<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>

会因为缺少右括号而产生语法错误。

应该是这样的:

<Link to={'/products/' + product.id + '/' + product.slug}>{product.name }</Link>

注意 product.slug 末尾的“}”

相关问题