【问题标题】:How to get props passed through Route using React Router如何使用 React Router 获取通过 Route 传递的道具
【发布时间】:2019-09-08 14:26:42
【问题描述】:

这是 App.js 中的路由

 <Router>
    <div>
      <Route path="/" component={App} />
      <Route path="/users" component={Users} />
      <Route  path='/dashboard'
       render={(props) => <Dashboard {...props} isAuthed={true} />} />
    </div>
  </Router>

如何在 Dashboard 组件中访问 isAuthed。要么使用生命周期 或者直接在构造函数中赋值给状态。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    这取决于您的用例。如果你想进一步改变传递的 prop,你可以使用像 componentDidUpdate 这样的生命周期方法。直接将 props 分配给 constructor 内部的 state 被认为是一种不好的做法,您可以直接使用 this.props.isAuthed 使用 props。

    请注意,在使用生命周期方法时,必须确保您不会不断地重新渲染组件。以下方法可能会派上用场。

    state = {
      isAuthed: false
    }
    
    componentDidUpdate(prevProps, prevState) {
      if(prevProps.isAuthed !== this.props.isAuthed) {
         this.setState({ isAuthed: this.props.isAuthed });
      }
    }
    

    通过只允许在isAuthed 更改时改变状态,您可以减少重新渲染的数量。或者,上面解释的更简单的方法,如果你不想改变 props,你可以直接使用 props。

    【讨论】:

    • componentWillReceiveProps(nextProps) { console.log(nextProps.isAuthed);这是正确的方法吗?
    • @AbhishekKonnur, componentWillReceiveProps 已弃用,请改用 componentDidUpdate。
    • 好的,我试试。谢谢
    • setState in componentDidUpdate 会导致额外的渲染(用户无法直接感知,但会减慢您的应用程序)。而且你的渲染方法不能假设状态已经准备好了(因为这不是第一次)。这就是我们需要使用getDerivedStateFromProps的原因。
    • setState 仅在道具更改时调用,因此进行检查。此外,componentDidUpdate 仅在发生更新时调用,否则根本不会调用。它会减慢应用程序的速度,这是怎么回事?你能举个例子吗?
    【解决方案2】:

    从 react blog,16.3 引入了 componentWillRecieveProps 的折旧通知。

    我建议你使用static getDerivedStateFromProps 方法来处理isAuthed 属性。

    以下代码用于根据 props 更新 isAuthed 状态变量。

    state = {
      isAuthed: this.props.isAuthed
    }
    
    static getDerivedStateFromProps(nextProps, prevState) {
      if (nextProps.isAuthed !== prevState.isAuthed) {
        return ({ isAuthed: nextProps.isAuthed}) // <- this is setState equivalent
      }
      etc...
    }
    

    希望这对你有用!

    【讨论】:

    • 派生状态会导致冗长的代码并使您的组件难以思考,更简单的替代方案是componendDidUpdate
    • 如果您需要执行副作用(例如,数据获取或动画)以响应道具的变化,请改用 componentDidUpdate 生命周期。哪种方法最适合您的用例,这完全取决于您兄弟。
    猜你喜欢
    • 2018-05-13
    • 2018-06-09
    • 2023-03-09
    • 2022-09-23
    • 2019-06-02
    • 2019-08-09
    • 2018-12-19
    • 2021-05-16
    • 2018-11-20
    相关资源
    最近更新 更多