gpt4 book ai didi

reactjs - 路由更改时重置组件的内部状态

转载 作者:行者123 更新时间:2023-12-03 13:35:06 25 4
gpt4 key购买 nike

我正在使用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>
);
});
};
}

最佳答案

我找到了解决方案。我没有放弃理解为什么状态为属性初始化器在重新安装时不会重置/初始化。我认为它只初始化一次,而不是每次路线更改时都会初始化] -

我想知道如何在路由更改时重置组件的状态。但事实证明你不必这样做。每个路由呈现一个特定的组件。当路由更改时,所有其他组件都会被卸载,并且这些组件的所有状态也会被破坏。 但是请参阅我的代码。我使用 es7+ propertyinitializer 来声明 state,count 。这就是为什么当组件在路由更改时重新安装时状态不会再次重置/初始化的原因。

为了解决这个问题,我所做的就是输入 state,initialProductNames,count;所有这些都进入构造函数。现在它工作得很好。

现在每次安装和重新安装都保持新鲜状态!!

关于reactjs - 路由更改时重置组件的内部状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48535110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com