Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

javascript - 如何在ReactJS中渲染通过道具的对象?(How to render object that pass through props in ReactJS?)

I am trying to render the data (object) that comes through props.

(我正在尝试渲染通过道具来的数据(对象)。)

However, I have got the following error:

(但是,出现以下错误:)


Uncaught TypeError: Cannot convert undefined or null to object Some how, I do not know why the data or object is null although the state of the data is updated during componentDidMount() .

(Uncaught TypeError: Cannot convert undefined or null to object尽管在componentDidMount()期间更新了data状态,但我不知道为什么数据或对象为null。)

Would you help me why the data is null?

(您能帮我为什么数据为空吗?)

Please look class A to see how the data is consumed

(请查看class A以了解如何使用数据)

class A extends React.Component {
  state = {
    data: null
  };

  componentDidMount() {
    this.data = this.props.location.state.data;
    this.setState({ data: this.props.location.state.data });
  }

  render() {
    return (
      <div>
        {Object.keys(this.data).map((key, index) => (
          <p key={index}> value is {this.data[key]}</p>
        ))}
        hello
      </div>
    );
  }
}

A.propTypes = {
  data: PropTypes.object,
  location: PropTypes.object
};
export default A;

Assume, this.data contains the data in the following format

(假设this.data包含以下格式的数据)

{
    id: 1,
    userName: "ABDXY",
    date: "01/12/2020",
    time: "21:00"
}
  ask by Daniel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this.data is not defined.

(未定义this.data 。)

You can access the data that is set in the state using this.state.data

(您可以使用this.state.data访问在状态中设置的数据)

Please ensure that this.props.location.state.data is not null

(请确保this.props.location.state.data不为null)

class A extends React.Component {
  state = {
    data: {}
  };

  componentDidMount() {
    // this.data = this.props.location.state.data;  => not required.
    this.setState({
      data: this.props.location.state.data
    });
  }

  render() {
    return ( <
      div > {
        Object.keys(this.state.data).map((key, index) => ( < 
          p key = {
            index
          } > value is {
            this.state.data[key]
          } < /p>
        ))
      }
      hello <
      /div>
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...