배열 (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 배열에 해당 객체를 추가하고 싶습니다. 하지만 오류가 점점 오전 :
Warning: setState(...): Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.Possible Unhandled Promise Rejection (id: 0): _this.state.selectedTags.push is not a function TypeError: _this.state.selectedTags.push is not a function
어떻게이 selectedTags 배열에 누를 태그 항목을 추가 할 수 있습니까?
와우 .. 나는 이것을 결코 깨닫지 못했다. 그 일이있어, 고마워. 이 개념에 대해 좀 더 이해할 수 있도록 도와 주시겠습니까? 이것과 같은 함수를 호출하면'onPress = {this.insertTag (tag)}'는 자동으로'render' 함수를 호출하고'onPress => {() = {this.insertTag (tag)}와 같은 함수를 호출합니다. }'는 press에서만 함수를 호출 할 것인가? –
안녕하세요, 화살표 함수를 설명하는 답변을 수정했습니다. –