react-navigation 无法在标题中插入我的 axios 的值; "undefined is not an object"
react-navigation can't insert value of my axios in the title; "undefined is not an object"
我试图将在我的 axios 中获得的值放在导航标题中,但我仍然有相同的错误消息。
这是我的代码:
fetchWeather () {
axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${this.state.city}&mode=json&units=metric&cnt=10&APPID=94c6cf0868fa5cb930a5e2d71baf0dbf`)
.then((response) => {
this.setState({report: response.data});
})
}
static navigationOptions = ({navigation}) => {
return {
title: `Météo de ${this.state.report.city.country}`,
tabBarIcon: () => {
return <Image source={require('./images/avatar.png')} style={{width: 20, height: 20}}/>
}
}
}
有人可以帮助我吗?
由于 navigationOptions
是一个 static
函数,它附加到 class 定义而不是实例。这意味着它不能使用 this
从特定实例获取数据,这就是为什么你得到 undefined
.
相反,您可以将数据设置到更全局的某个地方,例如 Redux 存储,并从那里读取它,或者使用 setParams:[= 将数据设置为导航状态的参数18=]
...
.then(response => this.navigation.setParams({report: response.data});
然后在你的 navigationOptions
:
title: `Météo de ${navigation.state.params.report.city.country}`
我试图将在我的 axios 中获得的值放在导航标题中,但我仍然有相同的错误消息。 这是我的代码:
fetchWeather () {
axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${this.state.city}&mode=json&units=metric&cnt=10&APPID=94c6cf0868fa5cb930a5e2d71baf0dbf`)
.then((response) => {
this.setState({report: response.data});
})
}
static navigationOptions = ({navigation}) => {
return {
title: `Météo de ${this.state.report.city.country}`,
tabBarIcon: () => {
return <Image source={require('./images/avatar.png')} style={{width: 20, height: 20}}/>
}
}
}
有人可以帮助我吗?
由于 navigationOptions
是一个 static
函数,它附加到 class 定义而不是实例。这意味着它不能使用 this
从特定实例获取数据,这就是为什么你得到 undefined
.
相反,您可以将数据设置到更全局的某个地方,例如 Redux 存储,并从那里读取它,或者使用 setParams:[= 将数据设置为导航状态的参数18=]
...
.then(response => this.navigation.setParams({report: response.data});
然后在你的 navigationOptions
:
title: `Météo de ${navigation.state.params.report.city.country}`