如何在响应本机中将json数组传递给Listview

时间:2018-09-17 10:45:16

标签: json react-native react-native-android

我正在尝试在React Native中实现Listview。我遵循了官方文档,但没有成功。基本上我从数据库中获得有关演员姓名及其各自姓氏的响应,如下所示

[
{"Name":"Amitabh","LastName":"Bachchan"},
{"Name":"Jaya","LastName":"Bhaduri Bachchan"},
{"Name":"Hrithik","LastName":"Roshan"},
{"Name":"Shahrukh","LastName":"Khan"},
{"Name":"Akshay","LastName":"Kumar"},

]

所以我想使用listview显示这些列表。 This is how i wanted to display Name

到目前为止,这是我的代码

constructor(props) {
 super(props);

  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
   this.state = {
  dataSource:ds.cloneWithRows(['row 1', 'row 2']),
};
}

 componentDidMount() {
  //this is where i get data from previous screen as i mentioned in above format then i pass to state
   this.setState({
     dataSource: this.props.source,
 })
}

<ListView
            dataSource={this.state.dataSource}
            renderRow={(rowData) => 

                <View 
                  style={styles.CanContainer}>

                  <View
                    style={styles.CanSubContainer}>

                      <View style={{flex: 1, alignItems: 'center'}}>
                        <Text style={styles.canTitles}>
                         {rowData.Name}
                        </Text>
                      </View>

                      <View style={{flex: 1, alignItems: 'center'}}>
                        <Text style={styles.canTitles}>
                          {rowData.LastName}
                        </Text>
                      </View>

                  </View>
                </View>  


            }
          />

以下是我尝试过的操作,但由于出现错误 This is the error what i am getting

1 个答案:

答案 0 :(得分:0)

您不能将数据直接分配给listview数据源。更改构造函数,并将listview数据源移动到全局状态。另外,您不能将JSON分配给listview数据源。您必须将JSON响应转换为javascript对象/数组。您可以为此使用JSON.parse()函数。

const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

export default class Example extends Component {
  constructor(props) {
    super(props)

    const myData = JSON.parse(props.source);

    this.state = {
      dataSource: ds.cloneWithRows(myData),
    }
  }

  render() {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData) =>
          <View
            style={styles.CanContainer}>
            <View
              style={styles.CanSubContainer}>
              <View style={{ flex: 1, alignItems: 'center' }}>
                <Text style={styles.canTitles}>
                  {rowData.Name}
                </Text>
              </View>
              <View style={{ flex: 1, alignItems: 'center' }}>
                <Text style={styles.canTitles}>
                  {rowData.LastName}
                </Text>
              </View>
            </View>
          </View>
        }
      />
    );
  }
}