【问题标题】:React Native displaying nested array itemsReact Native 显示嵌套数组项
【发布时间】:2019-09-15 16:39:14
【问题描述】:

下面的代码是针对单个帖子的,axios 获取当前帖子 ID 并将结果存储在帖子数组中。请记住,仅存储一个帖子,因为这是获取单个帖子。 ID 和日期显示正确,但如果我尝试显示嵌套项目(如渲染内容),它将不起作用。

API json 结果如下所示:

    constructor(props) {
    super(props);

    this.state = {
      post: []
    };
  }

getPost() {
    axios
      .get('single_post_api')
      .then(response => {
        this.setState({
          post: response.data
        });
      });
}

componentDidMount() {    
    this.getPost();
  }

render() {
const data = this.state.post;

  return ( 
  <View>    
          <Text>{data.date}</Text>
          <Text>{data.slug}</Text>

///Neither of these work///
          <Text>{data.content.rendered}</Text>
          <Text>{data.content[0]}</Text>
////////////////////////////

  </View>
  );
}

【问题讨论】:

  • 您不能只将html 作为反应中的值。
  • @HMR 我不确定你的意思是什么?
  • 在数据中content.rendered是html,你不能做&lt;div&gt;{content.rendered}&lt;/div&gt;,但必须按照我前面提到的方法去做(因为xss攻击)。你可以试试&lt;pre&gt;{JSON.sringify(data,undefined,2)}&lt;/pre&gt; 看看你哪里做错了。

标签: reactjs react-native axios


【解决方案1】:

试试这个。

render() {
  // If we run into a null, just render it as if we had an empty array.
  const posts = (this.state ?? this.state.posts) ? this.state.posts : [];

  return ( 
    <View>
      (posts.map((post, index) => (
        <View key={index}>
          <Text>{post.date}</Text>
          <Text>{post.slug}</Text>
          <Text>{post.content ? post.content.rendered : ""}</Text>
        </View>
      ));
  </View>
  );
}

【讨论】:

  • 常量数据 = this.state.post;是这个问题的拼写错误,我已在问题中修复它。我添加了 [response.data] 但仍然无法显示嵌套项。
  • 明白了。我修改了我原来的答案。
  • 这段代码有效,只是好奇为什么我不能只放 {post.content.rendered} ,为什么我需要在它之前: {post.content ? post.content.rendered : ""}
  • 你可以做 {post.content.rendered} 并且很好。但是,如果 post.content 曾经为 null,则会引发异常。
  • 如果我这样做,我会收到“未定义不是对象”错误,即使它是完全相同的帖子并且它可以正确显示 {post.content ? post.content.rendered : ""}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多