反应传递新道具

Sha*_*ode 2 javascript reactjs react-props

所以我在一个组件中更新我的状态,然后将新的props传递给子,但是孩子没有正确更新,输入的defaultValue没有改变.起初我以为可能是因为我正在使用this.props开始使用this.states并首先在那里应用新的道具但似乎没有工作.

父组件

this.state.newDetails == null ? '' : 
    <NewDetailsView details={this.state.newDetails} /> 
Run Code Online (Sandbox Code Playgroud)

子组件:

import React, { Component } from 'react';

class NewDetailsView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      details: (this.props.details!= null) ? this.props.details: null
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ details: nextProps });
    this.forceUpdate();
  }

  render() {
    return (
      <div>
        <input type="text" defaultValue={this.state.details.id} />
      </div>
    );
  }
}

export default NewDetailsView ;
Run Code Online (Sandbox Code Playgroud)

解决方案代码

待...

Viv*_*shi 7

问题在于componentWillReceiveProps:

this.setState({ details: nextProps });
Run Code Online (Sandbox Code Playgroud)

它应该是 :

this.setState({ details: nextProps.details });
Run Code Online (Sandbox Code Playgroud)

并且删除this.forceUpdate();,这里没有必要forceUpdate.


Sultion对第二个问题的改变defaultValue只是value:

<input type="text" value={this.state.details.id} />
Run Code Online (Sandbox Code Playgroud)

以下是工作示例的链接:

https://stackblitz.com/edit/react-parent-child-prop