代码之家  ›  专栏  ›  技术社区  ›  user944513

为什么我没有得到更新道具价值的反应

  •  1
  • user944513  · 技术社区  · 7 年前

    这是我的密码 https://stackblitz.com/edit/react-redux-basic-counter-1e8gdh?file=shared/components/NavBar.js

    - 。单击它可减小值。我的动作值是 decremented 但我不明白 updated value

     handle=()=>{
        this.props.decrement();
        this.getCount();
      }
    
      getCount=()=>{
        const {counter}= this.props;
        console.log(counter);
      }
    

    看我的 控制台.log

    预期输出为 -1

    电流输出为 0

    为什么?当我点击时,它显示输出 - 按钮

    1 回复  |  直到 7 年前
        1
  •  3
  •   TRomesh    7 年前

    原因是在控制台打印值时,道具没有更新。当道具更新后,react组件将重新渲染并显示计数器值。检查是否可以使用 setTimeout .

      handle=()=>{
        this.props.decrement();
        setTimeout(this.getCount,10)
      }
    

    您可以使用componentDidUpdate

       componentDidUpdate(prevProps) {
        if (this.props.counter !== prevProps.counter) {
          console.log(this.props.counter);
        }
      }
    

    或组件将接收道具(对于react版本<16)

      componentWillReceiveProps(newProps) {
      if( newProps.counter != this.props.counter ) {
        console.log(newProps.counter);
      }
    }
    

      static getDerivedStateFromProps(nextProps, prevState) {
      if(nextProps.counter !== prevState.counter ) {
         console.log(nextProps.counter);
      }
    }