不能只调用componentDidMount()。
一旦加载了组件,它就会自动执行。
不要在componentDidMount()中编写逻辑,而是编写一个单独的函数并调用该函数。
componentDidMount()是一个生命周期方法。
生命周期方法根据组件负载自动调用。
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
isLoading: true,
text: ''
}
}
callApi = (summonerIGN) => {
console.log("This is in summonerIGN", summonerIGN)
return fetch('https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/' + summonerIGN +'?api_key=<APIKey>')
.then((response) => response.json())
.then((responseJson) => {
console.log("This is in responseJson", responseJson)
console.log("This is the summoner ID: ", responseJson.id)
this.setState({
isLoading: false,
dataSource: responseJson,
summonerID: responseJson.id,
summonerName: responseJson.name,
})
})
.catch((error) => {
console.error(error)
})
}
render() {
return (
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Search For Summoner!"
onChangeText={(text) => this.setState({
text: text
})}
/>
<Button
onPress={() => {
console.log("This is in this.state.text", this.state.text)
this.callApi(this.state.text)
}}
title="Search"
color="#841584"
/>
<Text style={{padding: 10, fontSize: 20}}>
Searching for summoner: {this.state.text}
</Text>
<Text>
The summpner ID: {this.state.summonerID}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});