javascript - 为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?

标签 javascript reactjs react-native react-router react-redux

你能告诉我吗 为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?当我点击 button 时,它会调用函数 render 和 componentWillReceiveProps 但它显示 (this.props.val) 的不同值,为什么?

这是代码 https://codesandbox.io/s/g5119XP2Z

class App extends Component {
  update(){
    render(<App val={this.props.val + 1 }/>, document.getElementById('root'));

  }

  componentWillReceiveProps(nextProps){
    console.log(nextProps.val);
     console.log("====================");
      console.log(this.props.val,"val");

  }
  render(){
    console.log("render========")
          console.log(this.props.val,"val render");

    return (

  <div style={styles}>
    <button onClick={this.update.bind(this)}>{this.props.val}</button>
    <h2>Start editing to see some magic happen {'\u2728'}</h2>
  </div>
)

最佳答案

顾名思义,只要任何属性值发生更改,ComponentWillReceiveProps 就会触发,并且组件将在 nextProps 集合中接收它。因此,此事件会查找更改的值并使用新值更新组件的 props 集合。只有在 render 执行之后才有意义。

更多详细信息:

https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html

关于javascript - 为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395930/

相关文章:

javascript - 为什么 React Router v6 不渲染我的组件?

javascript - 如何在react js中继承图表属性

android - groovy.lang.MissingPropertyException : Could not get unknown property 'manifestOutputFile'

javascript - 离线私有(private) NPM 存储库

javascript - 获取超过 100 条消息

javascript数组似乎改变了我自己

react-native - 仅对一页 React Native 横向模式

javascript - React 初学者问题 : Textfield Losing Focus On Update

javascript - 如何在 React Redux 应用程序中打开和关闭内联对话框

android - react-native run-android 命令抛出 "java.net.ConnectException: Connection timed out"错误