javascript - 为什么我没有在 react 中获得更新的 Prop 值(value)

标签 javascript reactjs redux react-redux

你能告诉我为什么不在 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

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

最佳答案

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

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

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

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

或 componentWillReceiveProps(对于 React 版本 < 16)

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

或者 getDerivedStateFromProps( react 版本 16 +)

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

关于javascript - 为什么我没有在 react 中获得更新的 Prop 值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661821/

相关文章:

javascript - hapi.js 与 auth 相关

php - 将 png 图像从 JavaScript 传递到 PHP(错误 : Request-URI Too Large)

javascript - ChartJS - 雷达图选项不起作用

javascript - 函数在未被调用时执行

javascript - Ruby on Rails 与 React "TypeError: Object(...) is not a function"错误

javascript - Redux - Ngrx Action 调度异步处理

javascript - 使用react在父组件中执行子组件操作

javascript - 如何在获取图像之前调整图像大小?

reactjs - KeyboardAvoidingView 在 native react 中用过多的填充来推高内容

javascript - 当使用 Redux (React Native) 提供数据时,平面列表不会更新