【问题标题】:why I am not getting updated props value in react为什么我没有在反应中获得更新的道具价值
【发布时间】:2019-09-03 19:41:35
【问题描述】:

你能告诉我为什么不在 react 中获取更新的 props 值吗?

这是我的代码 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);
  }

查看我的 console.log

预期输出为 -1

当前输出为0

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

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

    如果你想控制台记录你的生命周期的价值。 你可以使用 componentDidUpdate

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

    或 componentWillReceiveProps(适用于 React 版本

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

    否则 getDerivedStateFromProps (react version 16 +)

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

    【讨论】:

    • 是的。我想发表我的答案。但你是第一个
    • prevState.counter 未定义
    • 状态中没有counter
    • @user944513 你用了什么生命周期?根据您的示例,您应该使用 componentWillReceiveProps()
    • @TRomesh 你能看看this 并更新你的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2021-02-22
    相关资源
    最近更新 更多