[英]React native change state loop
I'm building a react native app where a post
has comments
.我正在构建一个反应本机应用程序,其中一个post
有comments
。 I only want to show the comments
when the user clicks on load comments...
.我只是想显示comments
时,用户点击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):我试过了,但它不起作用(renderPost 是一个循环):
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...
.在上面的代码中,当用户单击load comments...
时,我将let fetchComments
设置为 true 。
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. renderPost 是一个功能组件,它没有自己的渲染和自己的状态,您可以通过其父 React.Component 中的 renderPost 道具传递一个更改状态的函数来解决这个问题。
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: renderPost 函数将接收它,如下所示:
const renderPost = (props) =>{
let fetchComments = props.fetchComments;
let setFetchComments = props.setFetchComments;
let item = props.item
let index = props.index
//...renderPost return remains the same
}
PS: 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. PS:如果你有多个 renderPost,你可以使用 fetchComments 作为一个布尔数组并将状态设置为 true 传递一个索引作为 setFetchComments 函数的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.