【问题标题】:why props show different value in render and componentWillReceiveProps?为什么 props 在 render 和 componentWillReceiveProps 中显示不同的值?
【发布时间】:2017-07-30 02:59:02
【问题描述】:

你能告诉我吗 为什么 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 在组件实际接收到这些新道具之前运行,这会触发重新渲染并更改 this.props.val 的值。您可以查看documentation for componentWillReceiveProps 了解更多信息。

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


【解决方案1】:

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

更多细节:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多