gpt4 book ai didi

javascript - 将数组作为属性传递

转载 作者:行者123 更新时间:2023-11-29 21:21:17 25 4
gpt4 key购买 nike

我想知道是否可以将数组的值作为标签内的值传递?例如下面的一段代码:

var itemfeed = this.state.jsonData.map((item,i) => {
return(
<View key={i}>
<TouchableHighlight val = {this.state.dataarray[i]} onPress={() => this.toggleExpanded2(i)}>
<View style={styles.header}>
<Text style={styles.headerText}>{item.date}</Text>
</View>
</TouchableHighlight>
<Collapsible collapsed={this.state.dataarray[i]} align="center">
<View style={styles.content}>
<Text>{item.Desc}</Text>
</View>
</Collapsible>
</View>
);

这是切换功能:

toggleExpanded2(i) {
var newarr = this.state.dataarray;
newarr[i] = !this.state.dataarray[i];

this.setState({
dataarray:newarr
})
this.setState({ collapsed: this.state.dataarray[i] });
console.log("index" + i + "value"+ this.state.dataarray[i]+ "collapsed"+ this.state.collapsed);
}

将项目映射到 View 元素。我正在尝试将一个数组的值作为一个值传递给 collapsed 属性,其中 collapsed 是一个 bool 值。但是,它似乎不起作用。我知道数组的值确实已定义。我想要做的是,当用户点击 View 时,该元素将显示并停留在那里,直到用户决定点击它并再次关闭它。是否显示取决于collapsed 的值。任何帮助将不胜感激。

最佳答案

不要将 setState() 视为同步操作,因为它可能不是:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Source


不要在调用 this.setState() 后立即读取 this.state,而是依赖于本地变异的新状态,例如:

toggleExpanded2(i) {
var newarr = this.state.dataarray.slice(0); // Create a shallow copy of `this.state.dataarray`, treating the state as immutable
newarr[i] = !newarr[i];

var newCollapsed = !newarr[i];

this.setState({
dataarray: newarr,
collapsed: newCollapsed
});

console.log("index" + i + "value"+ newarr[i]+ "collapsed"+ newCollapsed);
}

关于javascript - 将数组作为属性传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com