【问题标题】:Fetching document as JSON using React-Native使用 React-Native 以 JSON 格式获取文档
【发布时间】:2019-07-09 13:51:22
【问题描述】:

我找到了一些类似的解决方案,但没有一个完全符合我的要求。

这就是我想做的事情:我在服务器中有一些保存为 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');
  };
}

【问题讨论】:

  • 你的代码示例?
  • @AndreiOlar 我刚刚添加 :)
  • 对我来说不清楚你想做什么..你会在服务器上有多个文件吗?并想要获取所有这些?
  • @oma 是的,这就是我想做的。这里我只展示一个文档,但会有多个类似的文档。

标签: arrays json react-native fetch document


【解决方案1】:

我了解您要完成的工作。但我真的不认为你可以让它像你想要的那样工作。您可以将其与调用普通 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,那么您显然也需要在客户端上进行更改。

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

【讨论】:

  • 谢谢你的回答,但是,我想我已经在做同样的事情了。你在最后一句话中说的没错,我想让客户总是知道文档结构。文档的结构将始终相同,唯一的区别是例如:一个文档具有标题、内容和 2 个输入字段;第二个文档有标题、内容、图像和 5 个输入字段等。有没有办法只读取所选文档的内容?
  • 我可以只调用 Contract 而不指定 Contract.item 之类的内容吗?这样,无论在里面什么都可以。一个数组,它将被立即调用。
猜你喜欢
  • 2018-01-26
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2019-01-07
  • 1970-01-01
相关资源
最近更新 更多