对象无效作为React子级错误

时间:2018-05-23 10:53:35

标签: javascript reactjs

这是我对服务器的回复:

enter image description here

但是当我想在我的状态中设置它时,我收到了以下错误消息:

Objects are not valid as a React child (found: object with keys {id, eyecolor1}). If you meant to render a collection of children, use an array instead.
    in span (at Main.js:328)
    in div (at Main.js:327)
    in SingleDialog (at Main.js:264)
    in div (at Main.js:180)
    in Main (at Register.js:11)
    in div (at Register.js:9)
    in Register (created by Route)
    in Route (at App.js:23)

我的代码:

constructor(props){
    super(props);
    this.state = {
      date : {
        day : {
          1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14, 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20, 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26, 27: 27, 28: 28, 29: 29, 30: 30, 31: 31
        }
      },
      data:{

      }
    }

  componentWillMount(){
      this.getInitInfo();
  }


  getInitInfo(){

    userService.getInitInfo('WebApp','1','')
      .then(
        (response) => {
          console.log(response.data); //the output

          this.setState({data:response.data}) //error line


        }
      )
  }

我的错误行:

this.setState({data:response.data})

我错了什么?

1 个答案:

答案 0 :(得分:0)

state对象的格式错误,您需要检查响应是否为空。

this.setState({data: response.data})

更改您的代码

this.setState({data: response && response.data})