【发布时间】:2018-07-10 03:31:09
【问题描述】:
我正在使用 react-router-v4 和 react 16。
当用户转到不同的路线或返回相同的路线时,我想重置组件的内部状态。路由更改应该破坏组件的内部状态,但它不会。而且我什至找不到在路由更改时通知组件的方法,因为它是嵌套组件而不是Route 组件的直接渲染。请帮忙。
这是代码或live codepen example --
const initialProductNames = {
names: [
{ "web applications": 1 },
{ "user interfaces": 0 },
{ "landing pages": 0 },
{ "corporate websites": 0 }
]
};
export class ProductNames extends React.Component {
state = {
...initialProductNames
};
animProductNames = () => {
const newArray = [...this.state.names];
let key = Object.keys(newArray[this.count])[0];
newArray[this.count][key] = 0;
setTimeout(() => {
let count = this.count + 1;
if (this.count + 1 === this.state.names.length) {
this.count = 0;
count = 0;
} else {
this.count++;
}
key = Object.keys(newArray[count])[0];
newArray[count][key] = 1;
this.setState({ names: newArray });
}, 300);
};
count = 0;
componentDidMount() {
this.interval = setInterval(() => {
this.animProductNames();
}, 2000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
componentWillReceiveProps(nextProps) {
console.log(nextProps.match);
if (this.props.match.path !== nextProps.match.path) {
this.setState({ ...initialProductNames });
this.count = 0;
}
}
render() {
return (
<section className="home_products">
<div className="product_names_container">
I design & build <br />
{this.createProductNames()}
</div>
</section>
);
}
createProductNames = () => {
return this.state.names.map(nameObj => {
const [name] = Object.keys(nameObj);
return (
<span
key={name}
style={{ opacity: nameObj[name] }}
className="product_names_anim">
{name}
</span>
);
});
};
}
【问题讨论】:
-
能否提供您的路由代码
-
是的,为什么不呢。但这没有什么问题
-
我只是想你可以为位置设置一些全局状态,而在路由的onenter钩子中我们可以修改该状态并可以在组件中使用
-
react-router 的路由改变会破坏组件状态吗?
-
如果路由更改没有重置组件的内部状态,那么这是 react-router 的默认行为,在这种情况下,我们应该找到一种方法在路由更改时通知组件
标签: reactjs react-router react-router-v4 react-router-dom