首页 > 解决方案 > React-Native render json from fetch

问题描述

I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.

I have set the state as follows:

this.state = {
  loading: true,
  file: null,
  video: null,
  marks: []
};

and my fetch:

componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
  .then(response => response.json())
  .then((data) => {
    this.setState({
      loading: false,
      marks: data.mark
    }, () => {
      console.log(data.mark);
      console.log(this.state.marks);
      // const dataMap = data.mark.map((item) => {
      //   return {
      //     key: item.id,
      //     label: item.mark
      //   };
      // });
    });
  })
  .catch(err => console.log(err));

}

Now my render inside of the return:

 const { marks } = this.state;

      <FlatList
        data={marks}
        renderItem={({ item }) => <Text>{item.mark}</Text>}
        keyExtractor={(item, index) => index}
      />

Do I have to map the data then try to render it??

OUTPUT OF console.log(this.state.marks):

{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }

The mark is a pseudorandom string that can contain letters and numbers created on the backend

标签: jsonapidictionaryreact-nativerender

解决方案


因为 this.state.marks 是一个对象。首先,您需要将其转换为这种形式 [{}]。您可以进行以下更改以使其正常工作。

fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {

  let marks = [data.mark];  //Add this line

  this.setState({
    loading: false,
    marks: marks    // Change this line
  }, () => {  
       ....
 Rest of your code

推荐阅读