简体   繁体   English

如何从响应主体中获取深度嵌套的数据进入状态

[英]How to fetch deeply nested data from the response body into state

I've created a show page in react that is supposed to display the name of the selected student, the instrument(s) they play, and their assignments. 我已经在react中创建了一个显示页面,该页面应该显示所选学生的姓名,他们演奏的乐器以及他们的作业。

The database (simplified): user(student) data >many-to-many-relationship< instrument >many-to-many-relationship< assignment 数据库(简化):用户(学生)数据>多对多关系<仪器>多对多关系<分配

While I can pull a single user(student) object into state and display that student's name, accessing the associated instrument(s) and assignment(s) has been stumping me. 虽然我可以将单个用户(学生)对象拉入状态并显示该学生的姓名,但是访问相关的乐器和作业却令我很困扰。

Here's what the body.user looks like when I log it to the console: 这是我将它登录到控制台时body.user外观:

{user: {…}}
  user:
    assignments: Array(1)
      0: {id: 6, name: "Concert Cb Scale", description: "Record this 
         scale to Ensemble at the start of the …nscribe the scale if 
         your instrument requires it!", created_at: "2018-11- 
         24T22:16:51.460Z", updated_at: "2018-11-24T22:16:51.460Z"}
      length: 1
    __proto__: Array(0)
  first_name: "June"
  id: 10
  instrument_sections: Array(1)
    0: {id: 7, instrument: "french horn", created_at: "2018-11- 
       24T22:16:51.356Z", updated_at: "2018-11-24T22:16:51.356Z"}
    length: 1
    __proto__: Array(0)
  last_name: "Cenadaigh"

I can't seem to get at body.user.instrument_sections (and thenceforth to instrument: ). 我似乎无法获得在body.user.instrument_sections (和此后到instrument: )。 I haven't attempted getting at body.user.assignments since it looks to me like I'll get the same errors. 我没有尝试过body.user.assignments因为在我看来,我会遇到相同的错误。

The error in question is, from the console: "Error in fetch: Objects are not valid as a React child (found: object with keys {id, instrument, created_at, updated_at}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of StudentShow ." 有问题的错误来自控制台:“提取错误:对象作为React子对象无效(找到:键为{id,instrument,created_at,updated_at}的对象)。如果要渲染子代集合,使用数组代替或包裹使用createFragment(对象)从阵营附加的对象。检查的渲染方法StudentShow “。 I understand that it's having an issue that I'm pointing at an object within the user object, but I don't understand how to go about the suggestions the error makes. 我了解我在指向用户对象中的一个对象时遇到了问题,但是我不知道如何处理错误提出的建议。 Furthermore, if I try to change this.setState({ . . . instrumentSections: body.user.instrument_sections to include .instrument , the console comes back with simply undefined . 此外,如果我尝试将this.setState({ . . . instrumentSections: body.user.instrument_sections为包括.instrument ,则控制台将返回undefined

My further attempts to get at instrument have come from: 我进一步尝试使用instrument来自:

  1. Trying to figure out what should go between body.user.instrument_sections and .instrument (if anything). 试图弄清楚body.user.instrument_sections.instrument之间应该有什么关系(如果有的话)。

  2. How to map through body.user or the student state to get at the instrument and put it into state. 如何通过body.userstudent状态进行map以获取instrument并将其置于状态。 (Eventually, I'll have seed data that will have students with multiple instruments instead of just one, so I have that state held in an array.) (最终,我将获得种子数据,这些数据将使学生拥有多种乐器,而不仅仅是一种乐器,因此该状态保存在数组中。)

And finally, here's the code I currently have: 最后,这是我当前拥有的代码:

class StudentShow extends Component {
  constructor(props){
    super(props)
    this.state = {
      student: {},
      instrumentSections: [],
      assignments: []
    }
  }
  componentDidMount(){
    let studentId = this.props.params.id
    console.log(`${this.props.params.id}`)
    fetch(`/api/v1/users/${studentId}`)
    .then(response => {
      if (response.ok) {
        return response;
      } else {
        let errorMessage = `${response.status} 
        (${response.statusText})`;
        error = new Error(errorMessage);
        throw(error);
      }
    })
    .then(response => response.json())
    .then(body => {
      console.log(body);
      this.setState({ student: body.user, instrumentSections: 
        body.user.instrument_sections })
      console.log(this.state.student);
      console.log(this.state.instrumentSections);
    })
    .catch(error => console.error(`Error in fetch: ${error.message}`));
  }
  render(){
    return (
      <div className="text-center student-show">
        <h1>{this.state.student.first_name} 
          {this.state.student.last_name}</h1>
        <h2>Your section(s): </h2>
        <h4></h4>
        <h2>This week's assignment(s): </h2>
        <h4></h4>
      </div>
    )
  }
}

As you can see in your console instrument_sections is an array of objects so to get the first instrument for example you should get it like: 如您在控制台中所看到的, instrument_sections是一个对象数组,因此,例如,要获取第一个乐器,您应该像这样获取它:
body.user.instrument_sections[0].instrument . body.user.instrument_sections[0].instrument
and instead of instrumentSections: body.user.instrument_sections try 而不是instrumentSections: body.user.instrument_sections试试
instrumentSections: body.user.instrument_sections.slice() or instrumentSections: body.user.instrument_sections.slice()
instrumentSections: Array.from(body.user.instrument_sections)
and let me know if this solves your problem. 让我知道这是否解决了您的问题。

Me and the guy I worked with aren't sure if it's the most efficient method or if it's kosher with reactjs style, but at long last, the following javascript loop and accessories will work. 我和与我一起工作的人不确定这是否是最有效的方法,还是不知道它是否采用reactjs样式,但最终,以下javascript循环和附件将正常工作。 After .then(response => response.json()) : .then(response => response.json())

.then(body => { const sections = []; for(let i = 0; i < body.user.instrument_sections.length; i++){ sections.push(body.user.instrument_sections[i].instrument); };

And change the setState to this: 并将setState更改为此:

this.setState({ student: body.user, instrumentSections: sections)}

So what happens is js reaches into the body and through iteration grabs each relevant instrument, which goes into the sections array, and finally you set the state of instrumentSections equal to sections . 所以会发生什么是JS达到进入体内,并通过反复争夺每一个相关的仪器,该仪器进入sections阵列,最后你设定的状态instrumentSections等于sections

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM