首页 > 解决方案 > 已解决:是否将 json 对象输入函数但无法获取其数据?

问题描述

我试图将一个对象(评论)输入一个函数以返回一个渲染,但由于某种原因,我无法从放入的对象中获取数据,即使我知道它不是空的。当我执行 console.log("renderAuthorName comment:" + JSON.stringify(comment)); 它打印出整个评论对象:

renderAuthorName comment: {"item":{"id":6,"comment_object_type":4,"comment_object_id":8,"comment_author":1,"comment_author_name":"Nickname","comment_author_avatar":"default_avatar.png","comment_ts":"2020-06-08T01:19:04.000+0000","comment_content":"First comment here","comment_parent":0,"comment_parent_author":0,"comment_parent_author_name":null},"index":2,"separators":{}}

但是当我做 console.log("comment author name: " + comment.comment_author_name); 上线后,我得到

comment author name: undefined

为什么要这样做?我无法从 JSON 中打印字符串!!!这没有道理!有问题的函数是“renderAuthorName(comment)”。此外, render() 打印出来

this.props.comment: {"item":{"id":6,"comment_object_type":4,"comment_object_id":8,"comment_author":1,"comment_author_name":"Nickname","comment_author_avatar":"default_avatar.png","comment_ts":"2020-06-08T01:19:04.000+0000","comment_content":"First comment here","comment_parent":0,"comment_parent_author":0,"comment_parent_author_name":null},"index":2,"separators":{}}

未定义的作者导致注释单元格只打印出空白行,而不是任何文本,这就是问题所在。我需要它来打印评论内容。

这是有问题的完整 CommentCell 代码:

'use strict';

import React, { Component } from 'react';

import {
  Platform,
  StyleSheet,
  Text,
  Image,
  View,
  Modal,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
} from 'react-native';
import { connect } from 'react-redux';
import LoginPage from '../LoginPage';
import {showLoginPage, isLogin} from  '../actions/loginAction';
import URLConf from '../api/URLConf';
import {getToken} from '../util/Secret';
import Md5 from '../util/Md5';

const avatar_thumbnail = '?imageView2/1/w/48/h/48';

class CommentCell extends Component{

  constructor(props) {
    super(props);
    this.state = {
      loginRegPageVisible: false,
    };
  }

  onPress() {
    const {status,showLoginPage} = this.props;
    if(status == 'NOT_LOGGED_IN') {
      showLoginPage();
      return;
    }
    this.props.reply(this.props.comment);
  }

  renderAuthorName(comment) {
    console.log("renderAuthorName comment: " + JSON.stringify(comment));
    console.log("comment author name: " + comment.comment_author_name);
    console.log("comment props author name: " + this.props.comment.comment_author_name);
    //console.log("test: " + test);
    if(comment.comment_parent_author_name != undefined && comment.comment_parent_author_name != null) {
      console.log("renderAuthorName:1 ");
      return (<View style={{flex: 1, flexDirection: 'row'}}>
                <Text style={styles.username}>{comment.comment_author_name}</Text>
                <Text style={{fontSize: 14, color: '#9B9B9B', bottom: 1}}> Reply </Text>
                <Text style={styles.username}>{comment.comment_parent_author_name}</Text>
              </View>
            );
    } else {
      console.log("renderAuthorName:2 ");
      return (<Text style={styles.username}>{comment.comment_author_name}</Text>);
    }

  }

  render(){
    const {status} = this.props;
    console.log("this.props.comment: " + JSON.stringify(this.props.comment));
    return (
      <View >
        {status == 'NOT_LOGGED_IN' && <LoginPage {...this.props}/>}
        <TouchableOpacity onPress={()=>this.onPress()}>
          <View style={styles.commentBox}>
            {/* <Image style={styles.avatar} source={{uri:URLConf.IMG_BASE_URL+this.props.comment.comment_author_avatar+avatar_thumbnail}} /> */}
            <Image style={styles.avatar} source={require("../imgs/default-avatar.jpg")} />
            <View style={{flex:1,borderColor: 'red', borderWidth: 1}}>
                {this.renderAuthorName(this.props.comment)}
                {/* <Text style={styles.comment}>{this.props.comment.comment_content}</Text> */}
                <Text style={styles.comment}>Test comment style</Text>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  commentBox: {
    height: 100,
    flex: 1,
    flexDirection: 'row',
    borderColor: 'black',
    borderWidth: 1,
    padding: 10,
    paddingBottom: 4,
  },
  avatar: {
    borderRadius: 16,
    width: 32,
    height: 32,
    marginRight: 10,
  },
  username: {
    fontSize: 14,
    fontWeight: 'bold',
    color: 'black',
    // lineHeight: 13,
    marginBottom: 4,
  },
  commentTime: {

  },
  comment: {
    fontSize: 14,
    //color: 'black',
    color: '#030303',
    lineHeight: 18,
  },
});


export default connect((state) => ({
  status: state.isLogin.status, //登录状态
  loginPageVisible: state.showLoginPage.loginPageVisible
}), (dispatch) => ({
  isLogin: () => dispatch(isLogin()),
  showLoginPage: () => dispatch(showLoginPage()),
}))(CommentCell)

这是调用 CommentCell 并为其提供数据的 CommentList:

'use strict';

import React, { Component } from 'react';
import {
  FlatList,
  //ListView,
  Platform,
  StyleSheet,
  Text,
  Image,
  View,
  TouchableOpacity,
  TouchableHighlight,
  TouchableNativeFeedback,
} from 'react-native';

import PoplarEnv from '../util/PoplarEnv';
import CommentCell from './CommentCell';
import {getCommentsOfObject} from '../api/CommentAPI';
import URLConf from '../api/URLConf';

const avatar_thumbnail = '?imageView2/1/w/48/h/48';

export default class CommentList extends Component{
  constructor(props) {
    super(props);
    this.state = {
      // dataSource: new ListView.DataSource({
      //   rowHasChanged: (row1, row2) => row1 !== row2,
      // }),
      dataSource: [],
      loaded: false,
      replyModalVisible: false,
      commentsArray: [],
      commentCounter: this.props.commentCounter,
      commented: this.props.commented,
      limit: this.props.limit, //评论显示行数

      comment: null,
      commentBarVisible: false,
    };
  }

  componentDidMount() {
    this.fetchData();

  }

  /*
    被评论的feed类型
  */
  getCommentObjType(type) {
    var type_str = '';
    switch (type) {
      case PoplarEnv.COMMENT_OBJ_TYPE.POST:
        type_str = 'post';
        break;
      case PoplarEnv.COMMENT_OBJ_TYPE.PHOTO:
        type_str = 'photo';
        break;
      case PoplarEnv.COMMENT_OBJ_TYPE.ALBUM:
        type_str = 'album';
        break;
      case PoplarEnv.COMMENT_OBJ_TYPE.SPOST:
        type_str = 'spost';
        break;
      default:
        type_str = '';

    }
    return type_str;
  }

  fetchData() {
    var type_str = this.getCommentObjType(this.props.object_type);
    getCommentsOfObject(type_str, this.props.object_id,this.state.limit, (result, comments) => {
      this.setState({
        commentsArray: comments,
        // dataSource: this.state.dataSource.cloneWithRows(comments),
        dataSource: comments,
        loaded: true,
      });
    });
  }

  renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text>
          Loading...
        </Text>
      </View>

    );
  }


  setReplyModalVisible() {
    this.setState({replyModalVisible: true});
  }

  setReplyModalInVisible() {
    this.setState({replyModalVisible: false});
  }

  addNewComment(comment) {
    console.log('add new comment to comments list');
    console.log(comment);
    var commentsArray = this.state.commentsArray;
    commentsArray.push(comment);

    this.setState({
      // dataSource: this.state.dataSource.cloneWithRows(commentsArray),
      dataSource: commentsArray,
    });

  }

  componentWillReceiveProps(nextProps) {

    if(this.props.commentCounter == nextProps.commentCounter) return;

    if(nextProps.newComment != undefined && nextProps.newComment != null) {
        this.addNewComment(nextProps.newComment);
    }
  }

  render() {
    if(!this.state.loaded) {
      return this.renderLoadingView();
    }
    return this.renderCommentList(this.props.commentCounter);
  }


  showCommentBar() {
    this.setState({
      commentBarVisible: true,
    });
  }

  hideCommentBar() {
    this.setState({
      isComment: false,
      commentBarVisible: false,
    });
  }


  renderCommentList(commentCounter) {
    //console.log("dataSource 0:" + JSON.stringify(this.state.dataSource[0])); correct!
    if(commentCounter > 0) {
      console.log("commentCounter >0");
      return (
        <View>
          <TouchableOpacity style={styles.commentList} onPress={this.props.nav2FeedDetail}>
            <FlatList
              data={this.state.dataSource}
              extraData={this.state}
              renderItem={(comment)=>this.renderRow(comment, this.props.caller)}
            />
          </TouchableOpacity>
        </View>
      );
    } else {
      return (<View/>);
    }

  }

  renderAuthorName(comment) {
    if(comment.comment_parent_author_name != undefined && comment.comment_parent_author_name != null) {
      return (<View style={{flex: 1, flexDirection: 'row'}}>
                <Text style={styles.username}>{comment.comment_author_name}</Text>
                <Text style={{fontSize: 14, color: '#9B9B9B', bottom: 1}}> Reply </Text>
                <Text style={styles.username}>{comment.comment_parent_author_name}</Text>
              </View>
            );
    } else {
      return (<Text style={styles.username}>{comment.comment_author_name}</Text>);
    }

  }

  renderRow(comment, caller) {
    //console.log("renderrow json: " +JSON.stringify(comment));
    //console.log("renderdor com:" +comment);

    //console.log("caller:" + caller);
    if(comment == null || comment == undefined) {
      return (<View />);
    } else {
      if(caller == 'FeedCell') {
        return(
              <View style={styles.commentBox}>
                <Image style={styles.avatar} source={{uri:URLConf.IMG_BASE_URL+comment.comment_author_avatar+avatar_thumbnail}} />
                <View style={{flex:1}}>
                    {this.renderAuthorName(comment)}
                    <Text style={styles.comment}>{comment.comment_content}</Text>
                </View>
              </View>
        );
      } else if(caller == 'FeedDetail') {
        console.log(JSON.stringify(comment));
        return(
          <CommentCell comment={comment} reply={this.props.reply}/>
        );
      }
    }
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  commentList: {
    borderColor: 'red', borderWidth: 1,
    //flex:1,
    marginTop: -10,
    marginLeft:8,
    marginRight:8,
    paddingTop: 0,
  },
  commentBox: {
    flex: 1,
    flexDirection: 'row',
    //borderColor: 'black',
    //borderWidth: 1,
    padding: 10,
    paddingBottom: 4,
  },
  avatar: {
    borderRadius: 16,
    width: 32,
    height: 32,
    marginRight: 10,
  },
  username: {
    fontSize: 14,
    fontWeight: 'bold',
    color: 'black',
    // lineHeight: 13,
    marginBottom: 4,
  },
  commentTime: {

  },
  comment: {
    fontSize: 14,
    color: '#030303',
    lineHeight: 18,
  },
});

module.exports = CommentList;

完整的控制台输出:

[Mon Jun 08 2020 20:04:41.558]  LOG      this.props.comment: {"item":{"id":6,"comment_object_type":4,"comment_object_id":8,"comment_author":1,"comment_author_name":"Nickname","comment_author_avatar":"default_avatar.png","comment_ts":"2020-06-08T01:19:04.000+0000","comment_content":"First comment here","comment_parent":0,"comment_parent_author":0,"comment_parent_author_name":null},"index":2,"separators":{}}
[Mon Jun 08 2020 20:04:41.558]  LOG      renderAuthorName comment: {"item":{"id":6,"comment_object_type":4,"comment_object_id":8,"comment_author":1,"comment_author_name":"Nickname","comment_author_avatar":"default_avatar.png","comment_ts":"2020-06-08T01:19:04.000+0000","comment_content":"First comment here","comment_parent":0,"comment_parent_author":0,"comment_parent_author_name":null},"index":2,"separators":{}}
[Mon Jun 08 2020 20:04:41.559]  LOG      comment author name: undefined
[Mon Jun 08 2020 20:04:41.559]  LOG      comment props author name: undefined
[Mon Jun 08 2020 20:04:41.560]  LOG      renderAuthorName:2 

请让我知道它为什么这样做?以及如何修复它以便我可以显示我想要的文本?

标签: javascriptjsonreactjsreact-nativeredux

解决方案


我修好了它。我需要comment.item.comment_author_name 而不仅仅是comment.comment_author_name

谢谢克里斯 G


推荐阅读