【问题标题】:Render the same component with some state property changes on a certain route changes在某些路由更改上渲染具有某些状态属性更改的相同组件
【发布时间】:2018-09-25 16:37:36
【问题描述】:

如何根据路由更改组件的某些状态属性。所以,目前我有一个组件,我在其中定义了一个状态属性 showNotebook= true

   super(props);
      this.state = {
        showNotebook: true,
        flipper: true,
        deleteModalOpen: false
      }

我正在使用 react-router,我有这样的路由

<Route path='/submission/:id' component={SubmissionContainer}/>

所以现在我想要如果有人继续前进

 /submission/:id#comment.id=xyzz

它应该显示与上面相同的组件,但属性 showNotebook 设置为 false,因此它是具有所需更改的相同组件。

我知道之前在这里问过类似的问题,但找不到我的问题的确切解决方案。所以提前道歉。

【问题讨论】:

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


    【解决方案1】:

    您可以简单地从路由器道具中检查位置路径名以及id 查询参数是否存在,然后使用一些逻辑设置状态,如下所示:

    this.state = {
      showNotebook: () => {
        if (this.props.location.pathname === '/submission' && this.props.location.search)
          return false;
        return true;
      }
      ...
    }
    

    【讨论】:

    • 试过但它给了我:Uncaught TypeError: Cannot read property 'pathname' of undefined
    • 您需要使用 react-router-dom 库才能完成所有这些操作。
    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2022-11-29
    • 2020-09-18
    • 2012-05-07
    • 2021-02-20
    • 2019-04-28
    相关资源
    最近更新 更多