javascript - 在 React 中,根据之前和当前的 props,在哪里设置状态?

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

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

组件的位置来自 props.location.pathname,因此我需要一个事件,在其中我可以访问上一个和下一个属性,然后设置组件的初始外观但是,取决于是否应该进行转换:

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

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

最佳答案

你说过

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 .

看看 uncontroledEmailInput 组件在状态中保存上一个 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

关于javascript - 在 React 中,根据之前和当前的 props,在哪里设置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52483121/

相关文章:

javascript - 如何只允许一个事件的 useState

javascript - nextjs : Warning: Prop `className` did not match. 服务器: "x"客户端: "y"

reactjs - 使用路由器 react Material-UI

javascript - Angular $http $resource 相当于 PDF GET 请求

javascript - 如何在不重绘图表的情况下更新highchart中的钻取数据?

javascript - 插件的 Npm 依赖项

ajax - React-Router中ajax调用出现401错误时如何重定向到登录页面?

javascript - Typescript ,'NodeListOf<Element>' 不是数组类型也不是字符串类型

reactjs - 带有将输入字段更改为文本输入的选项的下拉菜单

javascript - React- Router,理解转换