我目前正在学习如何使用React Native创建应用程序,并且遇到了为什么我的应用程序刚开始运行时为什么运行该方法的问题?
我以为我只在按钮onPress上调用了componentDidMount()函数?
一切正常,但我不确定为什么会这样。
感谢您的帮助!
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
isLoading: true,
text: ''
}
}
componentDidMount(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.componentDidMount(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',
},
});
答案 0 :(得分:1)
您不能只调用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',
},
});