【问题标题】:Error When passing data between components在组件之间传递数据时出错
【发布时间】:2019-11-08 02:30:03
【问题描述】:

我正在尝试将值从一个组件 - Counters.jsx 传递到 Counter.jsx。当我转到开发人员控制台并执行日志时,我可以从以下位置获取数据:this.props.value 但是当我尝试将其设置为状态时,我收到以下错误:TypeError: Cannot read property 'value'的未定义。

// This is the component: Counters

import React, { Component } from "react";
import Counter from "./counter";

class Counters extends Component {
  state = {
    counters: [
  { id: 1, value: 4 },
  { id: 2, value: 0 },
  { id: 3, value: 0 },
  { id: 4, value: 0 }
  ]
};

render() {
return (
  <div>
    {this.state.counters.map(counter => (
      <Counter key={counter.id} value={counter.value} selected={true} />
    ))}
  </div>
);
}
}



// This is the component: Counter

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: this.props.value
  };

当我将状态 - Count 设置为 this.props.value 时,问题出在 Counter 类中。但是,如果我执行 console.log(this.props.value),则可以访问此值。

我收到此错误:未捕获的类型错误:无法读取未定义的属性“值”

有谁知道我是否遗漏了什么,为什么我可以使用 console.log 访问它但无法将状态计数设置为 this.props.value?

【问题讨论】:

    标签: reactjs components state prop


    【解决方案1】:

    您必须处理由于某种原因没有props.value 的情况。

    class Counter extends Component {
      state = {
        count: this.props.value || 0,
      };
    ...
    }
    

    在您的情况下,我认为您不必使用另一个 statevalue。 最好直接使用props 变量,而不是使用state 变量。

    【讨论】:

    • 我不这么认为,请检查一下。 codepen.io/minion/pen/VJMZbb
    • 在这种情况下使用默认道具
    • 这将与 -1 一起正常工作,因为它表示当存在 false ( 0,null,false ) 值但 -1 是 true 值时传递 0。
    【解决方案2】:

    在构造函数中设置:

    constructor(props) {
        super(props);
        this.state = {
          count: props.value,
        };
    }
    

    【讨论】:

    • @avinitish666:如果它适合你,你需要accept the answer
    • @huMptyduMpty 现在做到了。谢谢。
    【解决方案3】:

    您必须在构造函数中设置默认值并在 componentDidUpdate 方法中更新状态。

    constructor(props) {
        super(props);
        this.state = {
          count: 0,
        };
    }
    
    componentDidUpdate(prevProps, prevState) {
       this.setState({count : this.props.value });
    }
    

    【讨论】:

      【解决方案4】:

      您可能错过的是在构造函数中将 props 传递给 super。

      constructor(props) { 
        super(props); 
        this.state = { count:this.props.value, }; 
      }
      

      如果不将 this.props 传递给 super,则不能在构造函数中使用它。

      另外,作为答案之一,您需要在没有传递任何道具时处理案例。

      我建议你在这种情况下使用默认道具。

      查看here 了解默认道具和道具类型。

      【讨论】:

        【解决方案5】:

        将您的组件代码更改为:

        import React, { Component } from "react";
        
        class Counter extends Component {
          constructor(props){
            super(props);
            this.state = {
              count: this.props.value
            };
          };
        

        您正在尝试使用 this 而不提供适当的上下文。按照我的建议更改您的代码,它应该可以正常工作。 希望对你有帮助!!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-26
          • 2018-02-15
          • 2020-08-08
          • 2020-03-05
          • 1970-01-01
          • 1970-01-01
          • 2017-08-12
          相关资源
          最近更新 更多