【问题标题】:Display JSON data in React-Native without using a List?在 React-Native 中显示 JSON 数据而不使用列表?
【发布时间】:2018-05-20 00:33:46
【问题描述】:

我想知道如何使用 fetch API 获取 json 数据,然后在不使用 Lists(Flatlist、ListView 等)中的 data= 的情况下显示它。我正在考虑这样的事情:

    export default class HomeScreen extends React.PureComponent {
    constructor(props)
{

  super(props);

  this.state = {
  isLoading: true,
};

componentDidMount(){
     fetch(`http://www.example.com/React/data.php`, {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json',
     },
   }).then((response) => response.json())
       .then((responseJson) => {

      data = responseJson;
      this.setState({ loading: false });


   }).catch((error) => {
     console.warn(error);
   });

}

renderItems() {
  const items = [];
  this.data.foreach( ( dataItem ) => {
    items.put( <Text>{ dataItem.id }</Text> );
  } )
  return items;
}

render() {


    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }


      return(

         <View style = { styles.MainContainer }>
          <View>
           <Card>          
              <View>
              <Text>{this.renderItems()}</Text>
             </View>
           </Card>
           </View>
         </View>
       );
     }
const styles = StyleSheet.create({
  MainContainer: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#333',
  },
     }

我不确定它应该是什么样子,但是如果有办法做到这一点,那么我猜想这样做呢?任何帮助都将不胜感激!

这是对数据的响应:

Here is the response of the data:

{"id":"1","imagename":"dog"}{"id":"2","imagename":"cat"}{"id":"3","imagename":"mouse"}{"id":"4","imagename":"deer"}{"id":"5","imagename":"shark"}{"id":"6","imagename":"ant"}

【问题讨论】:

  • 好吧,先说几件事...您是否正在查看包含单个项目的 JSON 数据?或者它是一个项目数组?
  • @NemiShah 仅一项:{"id": "13", "imagename": "hello"}
  • 好吧,我的解释比我预期的要长,所以发布了一个答案。

标签: php json reactjs react-native


【解决方案1】:

这对我有用。

在构造函数中添加状态

  constructor(props) {
    super(props);
    this.state = {
      dataSource: ""
    };
  }

然后无论您如何获取数据,无论是生命周期方法还是普通函数,都可以正常获取数据。只需对我们之前创建的数据源执行setState

componentDidMount() {
    const data = new FormData();
    data.append("get_about", "true");
    fetch("https://www.example.com/api/About", {
      method: "post",
      body: data
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState({                                // ++++
          dataSource: responseJson                     // ++++
        });                                            // ++++
        console.log(dataSource);
      });
  }

现在,只需调用它:

render() {
    return (
      <View style={styles.container}>
        <Text>{this.state.dataSource.about_info}</Text>
      </View>
    );
  }

【讨论】:

    【解决方案2】:

    所以这是我会做的事情,但不一定是最好的方法。

    componentDidMount(){
     fetch('http://www.example.com/React/data.php', {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/json',
     },
     body: JSON.stringify({
       id : ?,
       imagename : ?,
    
     })
    
     }).then((response) => response.json())
         .then((responseJson) => {
    
          this.data = responseJson;
          this.setState({ loading: false });
    
    
     }).catch((error) => {
       console.error(error);
     });
    

    其中“数据”是组件类中的本地对象,加载只是一个标志,用于知道何时呈现数据。

    那么你的渲染方法会是这样的

    ...
    { !this.state.loading &&
        <View>
          <Text>{ this.data.id }</Text>
          <Text>{ this.data.imagename }</Text>
        <View>
    }
    ...
    

    渲染的组件当然可以更改为您喜欢的任何内容,但这将处理何时显示您的项目,并且可以从组件类中的任何位置访问数据。

    注意:您也可以将数据保持在状态中并跳过加载标志,但这是我通常的做法。

    此外,如果您想在 JSON 数据包含一组项目的情况下做同样的事情,您可以这样做。

    假设您的 JSON 响应是

    {
      [
       {
        title: 'title1'
       },
       {
        title: 'title2'
       }
      ]
    }
    

    执行类似的步骤将您的数据保存在本地对象中。创建一个类似的方法

    renderItems() {
      const items = [];
      this.data.foreach( ( dataItem ) => {
        items.put( <Text>{ dataItem.title }</Text> );
      } )
      return items;
    }
    

    然后在你的渲染方法中

    ...
    { this.renderItems() }
    ...
    

    希望这会有所帮助。

    【讨论】:

    • 当我尝试上面的第一个代码时,我得到了一个语法错误,所以我删除了JSON.stringify。然后出现另一个错误:undefined is not an object (evaluating '_this5.data.id') 还要注意我的评论中有多个示例数据。以防万一这可能是它的原因。@NemiShah
    • 所以代码中有一些空白,但如果没有适当的响应样本,我无法给你完整的答案......或者如果你能给我你正在点击的 URL,我可以浏览我自己的回复
    • 抱歉,我更新了我上面的问题并粘贴了 json 文件中的所有数据
    • 好的,我假设您的 json 数据是一个数组,其中包含所有这些单独的对象。在这种情况下,您可以使用我的答案的第二部分
    • 我使用了第二个答案,并确保所有细节都是正确的。我一直收到此错误:未定义不是对象(评估“this.data.foreach”)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多