javascript - 自动更新 react 组件中的值

标签 javascript reactjs

我正在尝试构建一个基于 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/

相关文章:

javascript - 如何在不使用验证码验证器的情况下实现Firebase电话验证系统?

javascript - 将一个组件导航到另一个组件时 react 中的最小 react 错误

javascript - React Redux 操作未调度,但请求成功

javascript - 不变违规 : _registerComponent(. ..):目标容器不是 DOM 元素

javascript - 从对象数组中的字符串中查找数值并进行计算

javascript - Javascript全页预加载器脚本修改

javascript - 查找与顺序无关紧要的嵌套数组的精确匹配

javascript - 在 pagespeed 中优先显示可见内容

javascript - 如何解决 'Redirect has been blocked by CORS policy: No ' Access-Control-Allow-Origin' header'?

javascript - 带有 Next.js 的 Firebase Analytics - 未定义窗口