Ruh*_*min 7 reactjs react-router react-router-v4 react-router-dom
我正在使用 react-router-v4 和 react 16。
当用户转到不同的路线或返回相同的路线时,我想重置组件的内部状态。路由更改应该破坏组件的内部状态,但它不会。而且我什至找不到在路由更改时通知组件的方法,因为它是嵌套组件而不是组件的直接渲染Route。请帮忙。
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>
);
});
};
}
Run Code Online (Sandbox Code Playgroud)
我得到了解决方案。我没有放弃理解为什么状态为在property initializer重新安装时不会重置/初始化。我认为它只初始化一次,而不是每次路线改变时] -
我想知道如何在路由更改时重置组件的状态。但事实证明你不必这样做。每个路由呈现一个特定的组件。当路由更改时,所有其他组件都会被卸载,并且这些组件的所有状态也会被破坏。但请参阅我的代码。我使用 es7+property initializer来声明 state,count。这就是为什么当组件在路由更改时重新安装时状态不会再次重置/初始化的原因。
为了解决这个问题,我所做的就是输入 state,initialProductNames,count; 所有这些都进入 constructor . 现在它工作得很好。
现在每次安装和重新安装都保持新鲜状态!
| 归档时间: |
|
| 查看次数: |
13518 次 |
| 最近记录: |