通过将某个组件的属性导入另一个组件来为其设置属性时,this.props返回未定义的错误

时间:2019-09-02 09:51:04

标签: reactjs

我有两个组成计数器和计数器的组件,其中我在计数器组件中导入了计数器,并为计数器组件添加了一些属性。

当我尝试在计数器组件的状态对象中修改计数器值时,它显示错误,因为无法读取未定义的值。

// Counters Component:

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 ({
      this.state.counters.map(counter => ())
    });
  }
}

Counter Component::
  state = {
    value: this.props.value,
    -- - > here this.props returns undefined.
    tags: []
  };

render() {
  `enter code here`
  console.log("props", this.props);
  -- -- > here props was printing in console.
}

1 个答案:

答案 0 :(得分:0)

代替:

state = {
    value: this.props.value,
    -- - > here this.props returns undefined.
    tags: []
  };

尝试一下:

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