make sure to pass up the same props that your component's constructor was passed

2,559 阅读1分钟

大家在通过reactjs编写app组件之间传值过程中,可能会遇到如下错误:

make sure to pass up the same props that your components's constructor was passed.

导致该问题的原因是因为我们在接收值的组件中没有在其constructor中添加对super方法调用的时候没有传入props变量,大家只要在接收值的component组件的constructor中在调用super方法的时候添加props变量即可,该变量表示了在外部构造组件的时候,组件所接收到的外部传入的值。该种方式通常发生在父组件像子组件传递值的过程中。

下面通过一个例子帮大家理解一下:

class List extends React.Component {
  constructor(props) {
    super(props);
    this.tag = props.tag;
    this.attributes = props.attributes;
    this.items = props.items;
  }
  render() {
    return React.createElement(
      this.props.tag,
      this.props.attributes,
      items.map(
        (n, i) =>
          new React.createElement(ListItem, {
            attributes: { n.attributes, key: i },
            value: n.value
          })
      )
    );
  }
}

class ListItem extends React.Component {
  constructor(props) {
    super(props);
    this.attributes = props.attributes;
    this.value = props.value;
  }
  render() {
    return React.createElement("li", this.props.attributes, this.props.value);
  }
}

const items = [
  { attributes: null, value: "A" },
  { attributes: null, value: "B" },
  { attributes: null, value: "C" },
  { attributes: null, value: "D" },
  { attributes: null, value: "E" }
];

const root = document.getElementById("root");

ReactDOM.render(
  new React.createElement(List, { tag: "ul", attributes: null, items }),
  root
);



相关资料:

stackoverflow.com/questions/5…