我正在创建 React Native 应用程序。我想将数组值设置为在 this.state:{current_Cat_id:'',} 中声明的变量。我的代码就像:-
render() {
return(
{this.props.data.map((dataImage,Index)=>
<View key={Index}>
{dataImage['main-head'] != undefined && (
<View style={{marginRight:20,marginLeft:20,marginBottom:20,width:320,fontSize:16,color:'#000'}}>
{dataImage['main-head'].map((subsubchild, Index3)=>
<Text>{subsubchild['cat_name']} ({subsubchild['num_rows']})
</Text>
)}
</View>
)}
</View>
)}
)
}
当我从循环中获取值时,它应该在我的变量中设置值,即在 this.state 中声明。我试过这样:
{this.props.data.map((dataImage,Index)=>
<View key={Index}>
{dataImage['main-head'] != undefined && (
<View style={{marginRight:20,marginLeft:20,marginBottom:20,width:320,fontSize:16,color:'#000'}}>
{dataImage['main-head'].map((subsubchild, Index3)=>
this.setState:({current_cat_id:subsubchild['cat_name']})
<Text>{subsubchild['cat_name']} ({subsubchild['num_rows']})
</Text>
)}
</View>
)}
</View>
)}
但不能成功。我怎样才能做到这一点
基兰,
最佳实践是不要修改 render() 中的状态。render() 应该使用 state 和 props 来确定渲染的 HTML 是什么。
如果您想根据 props 设置状态,最好的做法是在构造函数中或在 componentWillMount() 生命周期方法中。你会做这样的事情:
class ReactClass extends Component {
constructor(props) {
super(props)
this.state = {
# put initial values of state here or make them depend on props
}
}
componentWillMount() {
# access this.props here and use this.setState as needed
}
}
编辑
试试这个让状态拥有一个基于地图的数组如何:
componentWillMount() {
var ids = [];
this.props.data.map((dataImage) => {
ids.push(dataImage['ProductName'])
})
this.setState({current_cat_id: ids})
}
这可能并不完全有效,但这是我建议您构建列表然后立即设置状态的一般方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句