my reducer is:
const initialstate = { 1: { id: '1', user: 'user1', text: 'user1 comment', parentid: 0, }, 2: { id: '2', user: 'user2', text: 'user2 comment', parentid: 0, }, 3: { id: '3', user: 'user1', text: 'user1 subcomment', parentid: 2, }, 4: { id: '4', user: 'user2', text: 'user2 subcomment', parentid: 3, }, 5: { id: '5', user: 'user1', text: 'user1 subcomment', parentid: 2, }, }
i have mappedstatetoprops
, able show data using object.keys
, mapping it:
const rendata = object.keys(this.props.comments).map((key, idx) => { let comment = this.props.comments[key] return( <view key={idx}> <text> { comment.id } - { comment.user } - { comment.text} - { comment.parentid } </text> { rendatachild (comment.id) } // not sure </view> ) })
i want show objects
have parentid: 0
, show other objects below respective parent objects. want achieve :
what understand need add filter show objects have parentid: 0
, below add function (const rendatachild
) take current id
, show objects match parentid
passed id
. proper way it? how add filter , create const rendatachild
child objects?
please help. many thanks.
update1:
import react, { component } 'react'; import { text, view, alert } 'react-native'; var styles = require('../styles'); var styles1 = require('../styles1'); import { connect } 'react-redux'; class commentsnew extends component { constructor(props) { super(); } componentdidmount() { } rendercomments(commentid = 0) { return object.keys(this.props.comments) .filter(id => this.props.comments[id].parentid === commentid) .map((key, idx) => { const comment = this.props.comments[key]; const style = commentid === 0 ? styles.comment : styles.subcomment; <view style={style} key={idx}> <text> { comment.id } - { comment.user } - { comment.text} - { comment.parentid } </text> {this.rendercomments(comment.id)} </view> }); } render() { return this.rendercomments(); } } function mapstatetoprops(state) { return { comments: state.comments } } export default connect( mapstatetoprops ) (commentsnew);
error: commentsnew.render(): valid react element (or null) must returned. may have returned undefined, array or other invalid object.
have tried:
render() { return ( this.rendercomments(); ) }
same error
i think should render comments recursively because when render comment have loop through comments array find if there sub comments under current comment. (this code isn't tested, maybe errors):
rendercomments(commentid = 0) { return object.keys(this.props.comments) .filter(id => this.props.comments[id].parentid === commentid) .map((key, idx) => { const comment = this.props.comments[key]; const style = commendid === 0 ? styles.comment : styles.subcomment; return ( <view style={style} key={idx}> <text> { comment.id } - { comment.user } - { comment.text} - { comment.parentid } </text> {this.rendercomments(comment.id)} </view> ); }); } render() { return ( <view> {this.rendercomments()} </view> ); }
Comments
Post a Comment