React native change state loop

Jamie :

I'm building a react native app where a post has comments. I only want to show the comments when the user clicks on load comments.... The problem is how do I handle the state for each post (there are multiple posts). I tried this but it's not working (renderPost is a loop):

const renderPost = ({ item, index}) => {
    let fetchComments = false;

    return (
      <View style={[t.mB6]}>
        <View style={[t.roundedLg, t.overflowHidden, t.shadow, t.bgWhite, t.hAuto]}>

        <TouchableOpacity 
            key={item.id}
            onPress={() => {
              fetchComments = true;
            }}>
            <Text style={[t.fontBold, t.textBlack, t.mT2, t.mL4, t.w1_2]}>
                load comments...
              </Text>
          </TouchableOpacity>
        </View>

        { fetchComments ? <Comments postId={item.id}/> : null }
      </View>
    )
  }

In the code above I set let fetchComments to true when the user clicks on load comments....

Luiz Gustavo Abou Hatem De Liz :

renderPost is a functional component that doesn't have its own render and its own state, you may resolve this passing a function that changes state through renderPost props in its Father React.Component.

Example:

//imports

class FatherComponentWithState extends React.component{
  state={
    fetchComments:false,
    //(...OTHERSTUFFS)
    }

  setFetchComments = () =>{
    this.setState({fetchComments:true})
  }

  render(){
    return(
//(...FatherComponentStuffs)
      {new renderPost({
         setFetchComments: this.setFetchComments, 
         fetchComments:this.state.fetchComments,
         //(...renderPostOtherStuffs like item, index)
      })}
  //(...FatherComponentStuffs)
)}}

The renderPost function will receive it with something like this:

const renderPost = (props) =>{

let fetchComments = props.fetchComments;
let setFetchComments = props.setFetchComments;
let item = props.item
let index = props.index

//...renderPost return remains the same
}

P.S.: If you have multiple renderPosts, you can use fetchComments as an array of booleans and set the state to true passing an index as parameter of the setFetchComments function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34398&siteId=1