如何在哈希更改和更改状态时重新呈现组件

李明洋*_*李明洋 7 reactjs react-router

我想监视哈希更改,然后更改状态并重新呈现组件.所以我想知道在哪里监视组件生命周期中的哈希变化

例:

#/detail/:id  =>  #/detail

{info:[a:1,b:2]} => {info:[]}
Run Code Online (Sandbox Code Playgroud)

.#/ detail /:id和#/ detail是相同的组件

cap*_*ray 12

如果希望组件具有事件侦听器,则需要在componentDidMount中添加这些事件侦听器,并删除co​​mponentWillUmount中的事件侦听器.

componentDidMount() {
    window.addEventListener("hashchange", this.doSomething, false);
}

componentWillUnmount() {
    window.removeEventListener("hashchange", this.doSomething, false);
}
Run Code Online (Sandbox Code Playgroud)


Dea*_*ish 1

如果您想监视路由参数的变化,您可以使用生命周期方法来实现componentWillReceiveProps

组件WillReceiveProps

以此为契机,在调用 render() 之前通过使用 this.setState() 更新状态来对 prop 转换做出反应。旧的 props 可以通过 this.props 访问。在此函数内调用 this.setState() 不会触发额外的渲染。

componentWillReceiveProps: function(nextProps) {
  const {params: {id}} = nextProps;
  if(id !== this.props.params.id){
    /////////
  }
}
Run Code Online (Sandbox Code Playgroud)