【问题标题】:React router url changes correctly but component not being rendered from button component link反应路由器 url 正确更改,但组件未从按钮组件链接呈现
【发布时间】:2021-08-31 03:29:14
【问题描述】:

我有类似于以下CodeSandBox 示例的内容,我需要在两个不同的组件中使用反应路由。

我面临的问题是,如果使用这个代码框示例,我点击到 ProfileQuotes 组件级别,并假设我在每个底部组件中都有以下 Material-UI 按钮:

            <Button>
                text="New Item"
                variant="outlined"
                className={classes.newButton}
                component={NewItem} 
                to={'/new-item'}
            </Button>

当点击这个“新项目”按钮时,URL 会更改为正确的路由,即/new-item,但实际的NewItem 组件没有在页面中呈现?

如果我刷新浏览器,那么它会正确加载。

任何人都可以提供上述帮助吗?最好的解决方案是什么?

【问题讨论】:

  • 必须使用那里的链接

标签: javascript reactjs react-router material-ui


【解决方案1】:

您不应该使用按钮来更改转到新页面或转到新 URL。而不是使用 &lt;link to=""/&gt; 用于路由,但如果您想使用按钮转到不同的页面而不是使用 Redirect from react-router-dom

import { Redirect } from 'react-router-dom';
    const Next = (e) => {
    e.preventDefault();
    return <Redirect to='/NewItem' />;
    };
    <Button onClick={Next}>
         text="New Item" variant="outlined" className={classes.newButton}
         component={NewItem}
    </Button>;

或者你可以使用Link链接

import {Link} from 'react-router-dom';
    
    <Link to={'/NewItem'} className={classes.newButton}>
         New Item
    </Link>;

【讨论】:

  • 试过这个并收到错误:TypeError: e.preventdefault is not a function 有什么想法吗?
  • 我也尝试了Link,不幸的是这也没有用。不确定人们是否没有意识到,但我实际上是三个级别,因为我在两个单独的组件中有&lt;BrowserRoute&gt;。我需要以某种方式将此重定向或链接推送到父级别。
  • 是的,抱歉,这是我编辑的一个小错误。它应该是e.preventDefault();。如果它仍然不起作用,您可以添加 app.js 文件或您正在应用的文件&lt;BrowserRoute&gt;
【解决方案2】:

按钮将有一个 Link 的组件,它是从 react-router-dom 导入的

 <Button>
        text="New Item"
        variant="outlined"
        className={classes.newButton}
        component={Link} 
        to="/new-item"
 </Button>

app.js 中,您将创建一个Route,如下所示:

<Switch>
      <Route exact path="/NewItem" component={NewItem}/>
</Switch>

【讨论】:

  • 我实际上尝试过这个,但这实际上在Home 组件中渲染了组件NewItem,而不是直接回到App.js 级别。有什么想法吗?
  • 你的路线是这样的:` ` 听起来你缺少exact
【解决方案3】:

亚瑟,请确保在您的 index.js 或您声明开关的任何地方都这样设置。

<Switch>
      <Route exact path="/NewItem" component={NewItem}/>
</Switch>

然后你可以像这样简单地添加一个导航链接

<Link to="/NewItem">New Item</Link>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多