【问题标题】:"Requested keys of a value that is not an object" JSON and React Native“非对象值的请求键” JSON 和 React Native
【发布时间】:2017-08-22 10:43:43
【问题描述】:

我遇到了一个我无法解决的 React Native 问题,很可能是因为我对 React 和 JavaScript 还很陌生,所以我可能没有所有的“密钥”。哈哈

首先,这是我的 JSON 的结构:

{ "Spot[]": [
{"id":1,"name": "Relais Villenus"},
{"id":2, "name": "Random"}
]}

到目前为止,我还没有开始处理很多 JSON,但他们从来都不是这样的,这让我失去了信心!

我的班级请求数据:

class ListScreen extends Component{
static navigationOptions = {
  tabBarLabel: 'Liste',
};

constructor(props) {
  super(props);
  this.state = {
    isLoading: true
  }
}

componentDidMount() {
  return fetch(REQUEST_URL)
    .then((response) => response.json())
    .then((responseJson) => {
      let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.setState({
        isLoading: false,
        dataSource: ds.cloneWithRows(responseJson.Spot),
      });
    })
    .catch((error) => {
      console.error(error);
    });
}

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

  return (
    <View style={{flex: 1, paddingTop: 20}}>
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData) => <Text>{rowData.name}</Text>}
      />
    </View>
  );
}
}

根据我在这里或在 GitHub 上阅读的内容,我尝试了不同的方法,例如

dataSource: ds.cloneWithRows(responseJson.Spot[]),

或者像这样:

dataSource: ds.cloneWithRows(responseJson),

在视图中:

renderRow={(rowData) => <Text>{rowData.Spot.name}</Text>}

renderRow={(rowData) => <Text>{rowData.Spot[name]}</Text>}

我的代码使用这个 JSON:https://facebook.github.io/react-native/movies.json

这就是为什么我认为错误是因为我不知道如何正确获取数据。

谢谢!

【问题讨论】:

  • 试试这个ds.cloneWithRows(responseJson['Spot[]'])
  • 哦,非常感谢哈桑! :) 有用 !我确实尝试过 responseJson.['Spot[]'])。有一点:FML!再次感谢!

标签: javascript arrays json reactjs react-native


【解决方案1】:

您以错误的方式访问财产。把你dataSource改成

this.setState({
    isLoading: false,
    dataSource: ds.cloneWithRows(responseJson['Spot[]']),
});

您需要使用bracket notation 访问您的资源。

括号表示法需要一个计算结果为字符串的表达式(或可以强制转换为字符串),因此您可以使用任何字符序列作为属性名称。字符串可以包含的内容没有限制。

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多