【发布时间】:2016-12-20 03:38:28
【问题描述】:
所以我有这个 Picker 组件,对于项目,我从服务器获取数据并在状态更改时映射它。
//api.js
var api = {
getBooks() {
var url = 'http://192.168.43.14:8080/api/books/'
var headers = new Headers();
headers.append('Accept', 'application/json');
return fetch(url, headers)
.then((res) => res.json())
.catch(function(err) {
console.log('Fetch Error :-S', err);
throw Error(err);
});
}
}
//RegisterMobile.js
import api from '../utilities/api'
export default class RegisterMobile extends Component {
constructor(props) {
super(props)
this.state = {
books: [],
book: '',
mobile: '',
displayError: false,
error: 'Please provide a valid mobile number'
}
}
componentWillMount() {
api.getBooks().then((res) => {
this.setState({
books: res
})
})
}
render() {
return(
<View>
<View style={styles.selecBook}>
<Picker selectedValue={this.state.book} onValueChange={this.changeBook}>
{this.state.books.map((book) => {return <Picker.Item value={book.name} label={book.name} key={book.id} />})}
</Picker>
</View>
{this.state.displayError ? <Text style={styles.error}>{this.state.error}</Text> : null}
</View>
)
}
}
这工作正常。我得到了项目列表,当我点击 Picker 时,我可以选择项目。我想要做的是,如果在获取数据时出现任何错误(例如服务器已关闭),我想获取该错误并将其显示为错误(这将只是更改 error 和 @ 987654323@)。但是如果有一个将其设置为错误状态,我不知道如何获取错误。
【问题讨论】:
-
api.getBooks().then((res) => { this.setState({ books: res }).catch(e => this.setState({ displayError: true } )? -
@guest271314 嗨!我试过你的方法,但它给了我这个错误:
Possible Unhandled Promise Rejection (id: 0): this.setState is not a function TypeError: this.setState is not a function -
呃,你已经证明你知道如何在你的 API 中
catch(并重新抛出)错误,那么为什么它在组件中会有任何不同(除此之外你不会重新扔在那里)?
标签: javascript react-native es6-promise fetch-api