使用React-Native将文档作为JSON获取

问题描述 投票:1回答:1

我找到了一些类似的解决方案,但没有找到我想要的解决方案。

这就是我想做的事情:我在服务器中将一些文档保存为JSON,我想使用React-Native获取这些文档并在手机上显示它们。但是,当我每次将新文档上传到服务器时不必更改代码时,请考虑解决方案。 React-native应该能够从服务器获取所有内容,甚至是新文档,而无需在return {}中添加新的代码行。这些文档可能彼此不同,有些仅包括文本,有些包括文本和输入字段,有些包括图片,文本和输入字段。

如果不清楚,请在评论部分告诉我。任何建议都将受到高度赞赏!

JSON示例如何:

    {  
   "results":[  
      {  

         "contract":{  
            "title":"Contract test",
            "content":"You can always follow the progress of your application by logging on the the application portal. Please note that all communication from DTU will take place via this portal. When we have sent you a message on the ..."
         },

        "fillable_fields": {
            "FIELD_NAME_1": "FIELD_VALUE_1",
            "FIELD_NAME_2": "FIELD_VALUE_2",
            "FIELD_NAME_N": "FIELD_VALUE_N"
        },
         "picture":{  
            "medium":"https://www.healthcaredenmark.dk/media/11272/bridgeit_logo.png"
         }
      }
   ]
}

我在React-Native中的代码:

class HomeScreen extends React.Component {

  constructor() {

    super();
    this.state = {};
    this.getRemoteData();

  }


  static navigationOptions = {
    title: 'List of documents',
  };



  getRemoteData = () => {
    const url = "https://demo8106568.mockable.io/results";
    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: res.results
        });
      })
      .catch(error => {
        console.log("get data error from:" + url + " error:" + error);
      });
  };


  capFirstLetter = (string) => {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }


  renderNativeItem = (item) => {
    const contract =
      this.capFirstLetter(item.contract.title);
      //this.capFirstLetter(item.name.content);

    return <ListItem
            roundAvatar
            title={contract}
            subtitle={item.content}
            avatar={{ uri: item.picture.thumbnail }}
            onPress={() => this.onPressItem(item)}
          />;
  }


     onPressItem = (item) => {
     this.props.navigation.navigate('Detail', {item: item})
   }


  render() {
    return (
      <View>
        <FlatList
          data={this.state.data}
          renderItem={({item}) => this.renderNativeItem(item)}
        />
        {/* <Button
          title="Go Detail"
          onPress={() => this.props.navigation.navigate('Detail', {source: "homescreen"})}
        /> */}
      </View>
    );
  }
}





class DetailScreen extends React.Component {


  static navigationOptions = {
    title: 'Content of selected'
  };


  render() {

    const source = this.props.navigation.state.params.source;
    const item = this.props.navigation.state.params.item;
    let contract = "";
    let img = "";
    let inp = "";
    let content ="";

    if (item != null) {
      contract = item.contract.title;
      img = item.picture.medium;
      content = item.contract.content;
      inp = item.fillable_fields.FIELD_NAME_1;
    }


    return (

      <View style={styles.container}>

        <Text style={styles.text}>{contract} </Text>

        <Image
          style={{width: 300, height: 128}}
          source={{uri: img}}
        />

        <Text  style={styles.text} > {content} </Text>

        <TextInput style={{textAlign: 'center', borderWidth:1, marginBottom: 7, height: 50}} source={{uri: inp}}/>        

        <Button title="Go back to the list" onPress={this._goHome}/>

      </View>

    );
  }


  _goHome = async () => {
    this.props.navigation.navigate('Home');
  };
}
arrays json react-native fetch document
1个回答
0
投票

我理解你想要完成的事情。但我真的不认为你可以让它像你想要的那样工作。您可以将其与调用普通API端点进行比较。你很可能会有这样的方法:

getContracts() {
    fetch('CONTRACTS_ENDPOINT').then(res => doSomethingWithContracts(res))
}

您已经知道此数据会返回合同,并且您已经知道期望的数据。因此,您可以轻松访问contract.namecontract.date等字段。

当你想打电话给其他端点时,你会做类似的事情

getSomethingElse() {
    fetch('OTHER_ENPOINT').then(res => ...)
}

您将了解OTHER_ENPOINT附带的数据,因此您可以直接访问其字段。

所以我的建议是,将每个文档视为一个单独的API端点。当然,如果您更改文档,您还需要更改客户端实现,例如,如果您将contract.title重命名为contract.otherWordForTitle,那么您显然需要在客户端上更改它。

根据我所知,您想要的是让客户始终知道文档结构而不更新文档结构以便知道文档已更改,这是不可能的。但当然,我可能错了,可以有一个解决方法:-)

© www.soinside.com 2019 - 2024. All rights reserved.