错误在组件之间传递数据时

时间:2019-06-26 07:50:06

标签: reactjs components state prop

我正在尝试将一个组件-Counters.jsx的值传递给Counter.jsx。当我转到开发人员控制台并执行日志时,可以从以下位置获取数据:this.props.value,但是当我尝试将其设置为状态时,出现以下错误:TypeError:无法读取属性'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),则可以访问此值。

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

有人知道我是否错过了什么吗?为什么我可以使用console.log访问它,但是不能将状态计数设置为this.props.value?

5 个答案:

答案 0 :(得分:0)

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

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

就您而言,我认为您不必使用其他state值。 最好直接使用props变量,而不是使用state变量。

答案 1 :(得分:0)

在构造函数中设置它:

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

答案 2 :(得分:0)

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

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

componentDidUpdate(prevProps, prevState) {
   this.setState({count : this.props.value });
}

答案 3 :(得分:0)

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

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

在不将其传递给super的情况下,不能在构造函数中使用this.props。

此外,作为回答之一,您需要处理没有通过道具的情况。

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

选中here了解默认道具和道具类型。

答案 4 :(得分:0)

将您的组件代码更改为此:

import React, { Component } from "react";

class Counter extends Component {
  constructor(props){
    super(props);
    this.state = {
      count: this.props.value
    };
  };

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