我正在尝试构建一个基于 cookie 自动更新值的组件:
let cookies = 0;
(function count() {
cookies = document.cookie.split("?");
setTimeout(count, 10);
return cookies;
})();
class CartButton extends React.Component {
state = {quantity: cookies.length}
render() {
return (
<Cart onClick={e=>{show_cart()}}>
<Mfont>{this.state.quantity}</Mfont>
<Icon>shopping_cart</Icon>
</Cart>
);
}
}
“count”函数按预期工作,组件使用返回的最新值进行渲染。不幸的是,当“cookies”更改时它不会自动更新。它返回此错误:
Warning: render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render.
我在这里尝试了各种变体,但仍然无法弄清楚:/
最佳答案
componentDidMount
仅在组件首次加载时执行一次。这是编写页面加载后需要执行的任何逻辑的正确位置。
试试这个,
class CartButton extends React.Component {
//It is good to have a constructor for the component which has state
constructor(props){
super(props);
this.state = {quantity: cookies.length}
this.updateQuantity;
}
componentDidMount(){
this.updateQuantity = setInterval(()=> {
cookies = document.cookie.split("?");
this.setState({quantity: cookies.length})
},10)
}
//Don't forget to clear any setInterval like below
componentWillUnmount(){
clearInterval(this.updateQuantity);
}
render() {
return (
<Cart onClick={e=>{show_cart()}}>
<Mfont>{this.state.quantity}</Mfont>
<Icon>shopping_cart</Icon>
</Cart>);
}
}
关于javascript - 自动更新 react 组件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573529/