反应传递新道具

React passing new props

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

Parent 组件

this.state.newDetails == null ? '' : 
    <NewDetailsView details={this.state.newDetails} /> 

Child 分量:

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 ;

解决方案代码:

待处理...

const NewDetailsView = ({details}) => (
  <div>
    <input type="text" value={details? details.id: null} />
  </div>
);

问题在 componentWillReceiveProps:

this.setState({ details: nextProps });

应该是:

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

也去掉了this.forceUpdate();,这里就不需要forceUpdate了。


对第二期的建议将 defaultValue 更改为 value :

<input type="text" value={this.state.details.id} />

这里是 link 工作示例:

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

defaultValue 仅适用于初始加载。您应该控制输入并使用 props 来获取值(不需要 setState)。

React Passing

使用 getDerivedStateFromProps 而不是使用已弃用的 componentWillReceiveProps。可以找到它的一个例子 here

也许你和我一样遇到了这个问题,在 React v16.3.0 中,一些方法成为遗留的(不推荐使用),在这个例子中不要使用这个 componentWillReceiveProps,现在被称为 UNSAFE_componentWillReceiveProps 和可以借给你解决错误和错误。

而是看下面的例子:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.someValue !== prevState.someValue) {
      return {
        someState: nextProps.someValue,
      };
    } else return null;
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevProps.someValue !== this.props.someValue ) {
      this.setState({
        someState: this.props.someValue ,
      });
    }
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

这才是更新组件的正确方式。

参考:Replacing ‘componentWillReceiveProps’ with ‘getDerivedStateFromProps’