【问题标题】:Cannot setState from props in React from parent to child无法从 React 中的道具从父级到子级设置状态
【发布时间】:2018-11-07 00:27:13
【问题描述】:

我正在尝试将一些数据作为道具从父组件传递到子组件,并且我想将此道具设置为初始状态

class EditContact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: this.props.name,
      phone_number: this.props.phone_number,
      address: this.props.address
    };
    this.handleInputChange = this.handleInputChange.bind(this);
  }
  ...
}

我没有收到任何错误,但如果我 console.log this.state.name 我什么也得不到。或者当我在 chrome-s react add-on 中检查它时 我可以看到 props 值,但状态仍然是 ""

我也尝试在componentDidMount 中使用getDerivedStateFromProps 对其进行排序,我可以使用它进行设置,但是它不允许我稍后更改状态...为什么? !有什么问题?

【问题讨论】:

  • 你是如何在你的应用程序中使用这个EditContact 组件的?可能是您正在异步加载父组件中的数据,因此在创建 EditContact 时,尚未设置道具。
  • 请提供您要尝试的代码console.log

标签: reactjs setstate getderivedstatefromprops


【解决方案1】:

确保将 props 分配给 state 时,它​​们的值是预期的。

super(props);
debugger; // This will act as a break point in chrome

问题很可能是 props 的值在分配给状态时为空。

【讨论】:

  • 是的,这就是问题所在,但我似乎无法弄清楚如何解决它。我正在制作一个电话簿应用程序。过滤、排序、添加、删除、编辑。除了编辑之外,一切都完成了。为了能够完成项目,我应该将初始状态设置为 this.props 但是当它渲染时它仍然是空的,我不知道如何解决它。
  • 你可以使用 componentDidUpdate 并在那里执行 setState 但你必须小心并将其包装在条件中,否则会导致无限循环。当道具有价值时,您不能创建组件吗?我说这个原因是因为你必须做 setState 来改变你应该能够控制的 props 的值,我认为。
【解决方案2】:

使用

props.name

而不是

this.props.name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多