如何在路由更改时卸载组件

Ben*_*Ben 11 javascript reactjs

比方说,我在给定的路线上有一个组件 app.com/cars/1

我有一个链接到不同的汽车,例如侧边栏/cars/2,/cars/3等等.

我遇到的问题是当你改变链接时,比方说cars/1cars/2,组件没有卸载,我被componentWillReceiveProps解雇了.如果我转到另一个具有不同组件的页面,比如说/trucks,该组件已卸载且一切正常.

如何在路线更改时卸载组件?我有各种状态和助焊剂的东西,我想清除下一辆车.或者如果没有卸载,人们会处理这类问题的典型方式吗?我无法想象这不是很常见.

(注意我正在使用react-router)

Mic*_*ley 13

我认为处理此问题的正常方法是取消注册并重新注册您的侦听器,重置您的状态等等componentWillReceiveProps.围绕此行为创建抽象是正常的:

componentWillMount: function() {
  this.setupStuff(this.props);
}

componentWillUnmount: function() {
  this.tearDownStuff();
}

componentWillReceiveProps: function(nextProps) {
  this.tearDownStuff();
  this.setupStuff(nextProps);
}

setupStuff: function(props) {
  this.setState(this.getDataFromStore(props.store));
  props.store.listen(this.handler); // or whatever
}

tearDownStuff: function(props) {
  props.store.unlisten(this.handler); // or whatever
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您真的想重新安装组件,可以使用几个选项.

如果你不希望任何您的组件保持安装跨路由变化,你可以利用createElement选项的路由器的唯一关键词添加到组件:

function createElement(Component, props) {
  var key = ...; // some key that changes across route changes
  return <Component key={key} {...props} />;
}

// ...

<Router createElement={createElement}>
  ...
Run Code Online (Sandbox Code Playgroud)

但是,我不推荐这个.它不仅使你的应用程序变慢,因为每个路由组件每次都在重新安装,但它也完全禁用了具有不同道具的相同路由处理程序的后续渲染之间的动画.

如果您只想要某个路线始终重新渲染,您可以通过React.cloneElement以下方式在父母中为其指定密钥:

render: function() {
  var key = ...; // some key that changes across route changes
  return React.cloneElement(
    React.Children.only(this.props.children),
    {key: key}
  );
}
Run Code Online (Sandbox Code Playgroud)