[英]setState inside a static method
我想使用setState方法設置一個組件與另一個組件的狀態,因為這似乎涉及較少的編碼,但是我知道我不能在靜態方法中使用this關鍵字,這給我帶來了問題。 我想知道另一個解決此問題的方法。 幫助將不勝感激。
第一部分
class First extends Component {
filterByLocation(loc) {
const filteredData = this.state.passedInfo.filter(({area}) => area === loc);
this.setState({members: filteredData})
}
}
第二部分
class Second extend Component {
renderSuggestion() {
<TouchableOpacity
onPress = {()=> this.setState({location}, () => {
First.filterByLocation(this.state.location);
})}>
<Text> {"Click Me"}</Text>
</TouchableOpacity>
}
}
為什么不將整個對象傳遞給您的方法,例如:
<TouchableOpacity
onPress = {()=> this.setState({location}, () => {
Home.filterByLocation(this, this.state.location);
})}>
<Text> {"Click Me"}</Text>
</TouchableOpacity>
過濾方式:
filterByLocation(context, loc) {
const filteredData = context.state.passedInfo.filter(({area}) => area === loc);
context.setState({members: filteredData})
}
為了確保這不是一個好的做法,它應該可以解決問題,但又不應過度使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.