如何在 ReactJS 中渲染通过道具的对象?

我正在尝试渲染通过道具来的数据(对象)。但是,我遇到了以下错误:

Uncaught TypeError: Cannot convert undefined or null to object尽管data在componentDidMount(). 你能帮我为什么数据为空吗?


请看一下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;

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


{

    id: 1,

    userName: "ABDXY",

    date: "01/12/2020",

    time: "21:00"

}


皈依舞
浏览 173回答 2
2回答

森林海

this.data没有定义。您可以使用访问状态中设置的数据this.state.data请确保this.props.location.state.data不为空class A extends React.Component {&nbsp; state = {&nbsp; &nbsp; data: {}&nbsp; };&nbsp; componentDidMount() {&nbsp; &nbsp; // this.data = this.props.location.state.data;&nbsp; => not required.&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; data: this.props.location.state.data&nbsp; &nbsp; });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return ( <&nbsp; &nbsp; &nbsp; div > {&nbsp; &nbsp; &nbsp; &nbsp; Object.keys(this.state.data).map((key, index) => ( <&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; p key = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; index&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } > value is {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.state.data[key]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } < /p>&nbsp; &nbsp; &nbsp; &nbsp; ))&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; hello <&nbsp; &nbsp; &nbsp; /div>&nbsp; &nbsp; );&nbsp; }}

海绵宝宝撒

从状态中获取数据而不是this.data因为它不会在this.data更新时触发渲染。也{}用作默认值class A extends React.Component {&nbsp; state = {&nbsp; &nbsp; data: {}&nbsp; };&nbsp; componentDidMount() {&nbsp; &nbsp; const data = {&nbsp; &nbsp; &nbsp; id: 1,&nbsp; &nbsp; &nbsp; userName: "ABDXY",&nbsp; &nbsp; &nbsp; date: "01/12/2020",&nbsp; &nbsp; &nbsp; time: "21:00"&nbsp; &nbsp; };&nbsp; &nbsp; this.setState({ data });&nbsp; }&nbsp; render() {&nbsp; &nbsp; const { data } = this.state;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {Object.keys(data).map((key, index) => (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p key={index}> value is {data[key]}</p>&nbsp; &nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; &nbsp; &nbsp; hello&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}export default A;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript