[英]Insert the pressed item into an array in react-native
我在數組( tagList )中有一個標記對象列表,我正在從服務器中提取該對象並將其存儲到狀態中。 成功獲取后,我正在ScrollView
映射每個項目。
export default class RegisterTags extends Component {
constructor(props) {
super(props)
this.state = {
tagList: [],
selectedTags: [],
}
}
componentWillMount() {
api.getTagsOnRegister()
.then((res) => {
this.setState({
tagList: res
})
})
}
insertTag = (tag) =>{
this.setState({
selectedTags: this.state.selectedTags.push(tag)
})
}
render() {
return(
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.ScrollViewContainer}>
{this.state.tagList.map((tag) => {
return(
<View style={styles.tagStyle} key={tag.id} onPress={this.insertTag(tag)}>
<Text style={styles.tagText}>{tag.name}</Text>
</View>
)
})}
</ScrollView>
</View>
)
}
}
我想要實現的是,當我按下任何標簽時,我想將該對象添加到selectedTags數組中。 但我得到了錯誤:
警告:setState(...):在現有狀態轉換過程中(例如在
render
或另一個組件的構造函數中)無法更新。 渲染方法應該純粹是道具和狀態的函數; 構造函數的副作用是反模式,但是可以將其移至componentWillMount
。可能的未處理的承諾拒絕(id:0):_this.state.selectedTags.push不是函數TypeError:_this.state.selectedTags.push不是函數
如何將按下的標簽項添加到selectedTags數組中?
onPress={this.insertTag(tag)}
問題 :在render
函數中,您正在直接調用更改狀態的函數。 Render
函數永遠不要調用任何更新狀態的函數。
那么如何調用onPress
呢?
答:如下
onPress = {() => {this.insertTag(tag) }}
代碼現在可以工作了嗎? 答案是否定的。
您必須將視圖放入TouchableHighlight
並將onPress
方法從View
移至TouchableHighlight
。 然后希望您的代碼可以工作。 我假設一切都是安裝程序屬性。
~~~~~~編輯1 ~~~~~~~~~
What't之間的差 onPress={this.insertTag(tag)}
和 onPress = {() => {this.insertTag(tag) }}
花括號中的所有東西都是react jsx中的表達式 。 現在onPress={this.insertTag(tag)}
對花括號內的表達式求值並將其分配給onPress屬性,在您的情況下, this.insertTag
恰好會更新狀態。
當onPress = {() => {this.insertTag(tag) }}
,在計算花括號時會返回一個函數,但不會調用該函數。 當觸發onPress事件時,將調用該函數。
谷歌“箭頭功能”更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.