简体   繁体   English

在React组件安装上获取URL参数的正确方法?

[英]Proper way to get URL params on React component mount?

I have a component for which I want to get URL params (say, a1 and a2). 我有一个想要获取URL参数的组件(例如a1和a2)。 If these contain anything, I want to set some local state to their values so things can be rendered on the page. 如果这些包含任何内容,我想将某些本地状态设置为其值,以便可以在页面上呈现内容。 I'm using react-router-dom and the withRouter HOC, so I can access location from props , but I'm not sure if I can use that. 我正在使用react-router-domwithRouter HOC,所以我可以从props访问location ,但是我不确定是否可以使用它。 Right now I have: 现在我有:

class Example extends Component {
    constructor(props) {
    super(props);

    this.state = {
      a1: null,
      a2: null,
    }
  }

  componentDidMount() {
    console.log(window.location.search);
    const parsed = querystring(window.location.search);
    this.setState({
      a1: parsed.a1,
      a2: parsed.a2,
    })
  }
}

Now, doing this gives me an ESLint warning for Do not use SetState in ComponentDidMount . 现在,这样做会给我一个ESLint警告,提示Do not use SetState in ComponentDidMount I've done some searching and that's apparently 'ok' to do in a callback from componentDidMount , but this isn't a callback, so I'm not sure if it's 'ok'. 我已经做了一些搜索,在componentDidMount的回调中显然可以,但这不是回调,因此我不确定是否可以。

So what's the right thing to do here? 那么在这里做什么是正确的呢? Do I ignore the warning (and get the double-render)? 我是否会忽略警告(并进行两次渲染)? Is there some other way to properly get URL params and set them to local state? 还有其他方法可以正确获取URL参数并将其设置为本地状态吗?

I also don't want to use any methods that will be deprecated in React 17, since that just means re-writing it on upgrade... 我也不想使用任何将在React 17中弃用的方法,因为那只是意味着在升级时重写它...

Is there a particular reason why you are storing these values in the state? 在状态中存储这些值是否有特定原因?

You said it was "so things can be rendered on the page" 您说这是“以便可以在页面上呈现内容”

However, you don't need to use the state for that. 但是,您不需要为此使用状态。 In render() , you can access and use this.props . render() ,您可以访问和使用this.props

You should use componentWillMount method instead. 您应该改用componentWillMount方法。 It'll be preparatory setup and once state is set, your component can render normally, unlike re-render in case of componentDidMount . 这将是准备性的设置,并且一旦设置了状态,您的组件就可以正常渲染,这与componentDidMount情况下的重新渲染不同。

In case you don't want to use componentWillMount because of deprecation in future ( UNSAFE_ is still valid even after React 17 though), you can also set url params in constructor itself, as this are constant value and do not change at all. 如果您由于将来的弃用而不想使用componentWillMount (即使在React 17之后, UNSAFE_仍然有效),您也可以在constructor本身中设置url参数,因为这是常量值,根本不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM