【问题标题】:react-router can't jump to the pagereact-router 无法跳转到页面
【发布时间】:2018-10-18 23:07:31
【问题描述】:

我在我的项目中使用 react-router-dom,但我是新手。我有一个页面跳转的问题,这是我的 App.js 代码:

 class App extends Component {
  render() {
    return (
      <div className="App">
        <Switch>
          <Route
            path="/userrestaurant"
            render={props => <UserRestaurant {...props} />}
          />
          <Route path="/userrestaurant/edit/:id" component={EditRestaurant} />
        </Switch>
      </div>
    );
  }
}

export default App;

这是 UserRestaurant 组件的代码:

 export default class UserRestaurant extends Component {
  edit = () => {
    var restId = 4;
    this.props.history.push(`/userrestaurant/edit/${restId}`);
  };

  render() {
    return (
      <div>
        <Button onClick={this.edit}>Edit</Button>
      </div>
    );
  }
}

如果我单击编辑按钮,它应该会跳转到 EditRestaurant 组件,因为我已经在 App.js 中定义了路线。但是当我点击按钮时,只有 url 改变,页面停留在 UserRestaurant 组件中。

【问题讨论】:

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


    【解决方案1】:

    除非您添加 exact 属性,否则 &lt;Route/&gt; 会在 URL 上进行部分匹配。换句话说,/userrestaurant/edit/blah 仍然匹配Switch 的第一种情况,所以UserRestaurant 仍然被渲染。要么添加exact,这样第一个URL 仍然不匹配第二个URL,要么重新排序你的路由,让更具体的路由优先。

    class App extends Component {
      render() {
        return (
          <div className="App">
            <Switch>
              <Route
                path="/userrestaurant"
                exact
                component={UserRestaurant}
              />
              <Route 
                path="/userrestaurant/edit/:id" 
                component={EditRestaurant} />
            </Switch>
          </div>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2015-04-19
      • 1970-01-01
      • 2017-04-09
      • 2022-01-14
      • 2016-01-16
      • 2021-01-29
      • 2018-12-29
      相关资源
      最近更新 更多