【问题标题】:Where to set state, dependent on previous and current props, in React?在 React 中,根据先前和当前的 props 在哪里设置状态?
【发布时间】:2018-09-25 01:11:53
【问题描述】:

我使用componentWillReceiveProps 生命周期事件来启用或禁用到下一页的转换。现在这个事件改成了UNSAFE_componentWillReceiveProps,我觉得我不应该再用它了,但是我找不到明显的替代品。

组件的位置来自props.location.pathname,所以我需要一个事件,我可以在其中访问上一个和下一个道具,然后根据是否应该有过渡来设置组件的初始外观,但是:

  • getDerivedStateFromProps 只能访问以前的道具。
  • shouldComponentUpdate 应该用来告诉组件它是否应该更新,这不是我们想要的,所以它被淘汰了。
  • render 没有以前的道具。
  • getSnapshotBeforeUpdate 将参数传递给componentDidUpdate,此时组件已经渲染,所以无法设置初始外观。

我想我可以保存以前的路径名并下次在render 中使用它,但这似乎不是一个优雅的解决方案。在这种情况下,最佳做法是什么?

【问题讨论】:

    标签: javascript reactjs react-router react-transition-group


    【解决方案1】:

    你说过

    getDerivedStateFromProps only has access to the previous props.
    

    但 getDerivedStateFromProps 可以访问下一个 props 和上一个状态

    我同意,保存以前的路径名可能看起来不太优雅,但它是这里提供的替代方法:https://codesandbox.io/s/rjyvp7l3rq 在这里找到 https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html

    看看 uncontrolledEmailInput 组件在 state 中保存 prev props

    state = {
        email: this.props.defaultEmail,
        prevPropsUserID: this.props.userID
      };
    
      static getDerivedStateFromProps(props, state) {
        // Any time the current user changes,
        // Reset any parts of state that are tied to that user.
        // In this simple example, that's just the email.
        if (props.userID !== state.prevPropsUserID) {
          return {
            prevPropsUserID: props.userID,
            email: props.defaultEmail
          };
        }
        return null;
      }
    

    这是一篇关于新生命周期的精彩文章:https://medium.com/@baphemot/understanding-react-react-16-3-component-life-cycle-23129bc7a705

    【讨论】:

    • 谢谢,我想这是最好的解决方案。我仍然不喜欢它,因为您将有一个额外的状态来检查以前的路径。
    • 您好,如果在构造函数中我们已经在props.location.pathname 中获得了最新的路由路径,您如何使用先前的路由路径启动状态?
    【解决方案2】:

    你可以在下面使用 Reactjs 推荐的安全和推荐

    componentDidUpdate(prevProps) { 
    
         if (this.props.userID !== prevProps.userID) {
    
            this.fetchData(this.props.userID); 
    
        }
     }
    

    【讨论】:

    • 如果页面外观发生变化,这不会重新渲染组件并导致闪烁吗?我在这里做一个完整的背景转换,所以如果初始状态不正确,整个页面都会更新。
    • 正确的完整组件将被重新渲染,所以我认为不会发生闪烁。
    【解决方案3】:

    根据 react 文档,您应该使用 componentDidUpdate。它可以访问 prevProps,prevState 和 current props,state in this.props,this.state。

    查看文档 https://reactjs.org/docs/react-component.html#componentdidupdate

    componentDidUpdate(prevProps) {
        if(this.props.pathname !== prevProps.pathname) {
          //do something here or setState to adjust the appearance accordingly
        }
    }
    

    【讨论】:

    • 我会问你我问过其他人的问题,他的回答相同:“如果页面外观发生变化,这不会重新渲染组件并导致闪烁吗?我是在此处进行完整的背景转换,因此如果初始状态不正确,则整个页面都会更新。”
    猜你喜欢
    • 2017-07-18
    • 1970-01-01
    • 2017-10-19
    • 2021-03-28
    • 2019-08-23
    • 2013-01-07
    • 1970-01-01
    • 2016-10-27
    • 2019-02-28
    相关资源
    最近更新 更多