Javascript 异步设置状态不在componentDidMount中工作,但在其他位置工作:React Native
我的计划是从http请求中获取一个字符串数组,该数组的头中有一个授权令牌,然后使用该数组决定呈现什么(多个组件意味着用户是管理员,因此他将被发送到listView e.t.c) 我如何存储授权令牌:(react本机路由器流量用于导航) 在第二页有Javascript 异步设置状态不在componentDidMount中工作,但在其他位置工作:React Native,javascript,asynchronous,react-native,state,es6-promise,Javascript,Asynchronous,React Native,State,Es6 Promise,我的计划是从http请求中获取一个字符串数组,该数组的头中有一个授权令牌,然后使用该数组决定呈现什么(多个组件意味着用户是管理员,因此他将被发送到listView e.t.c) 我如何存储授权令牌:(react本机路由器流量用于导航) 在第二页有 var HotelAdminService = require('./services.js'); .... constructor(props) { super(props); this.state={ keyLoaded:false,
var HotelAdminService = require('./services.js');
....
constructor(props) {
super(props);
this.state={
keyLoaded:false,
};
this.tester= HotelAdminService.tester.bind(this);
}
componentDidMount() {
HotelAdminService.tester.bind(this);
}
render() {
console.log(this.state);
if (!(this.state.keyLoaded) ) {
return this.renderLoadingView();
}
return (
<View style={styles.viewContainer} >
<SearchBar onChangeText={(e) => this.clickMovie(e)}> </SearchBar>
<ListView dataSource={this.state.dataSource} renderRow= {this.renderMovie} style={styles.listView}/>
</View>
);
}
现在我知道这个方法是有效的,因为它做了我想要它做的事情,但是只有当我从第二页的按钮点击调用它时。但是,我想做的是在开始时让HotelAdmin.tester工作,以便在我获取数据时可以重新渲染。正如您所看到的,我的渲染方法会提供一个加载屏幕,直到keyLoaded变为true。也许一种替代方法是使用tester方法返回字符串,而不是更改状态,但是我无法从嵌套的promise调用返回字符串数组
在当前情况下,代码会停留在加载屏幕中,因为HotelSystemAdmin.tester不会运行并更改状态您只是将函数绑定到
componentDidMount
中的上下文。您需要调用它:
hoteladmin.tester.bind(this)()代码>
var HotelAdminService = require('./services.js');
....
constructor(props) {
super(props);
this.state={
keyLoaded:false,
};
this.tester= HotelAdminService.tester.bind(this);
}
componentDidMount() {
HotelAdminService.tester.bind(this);
}
render() {
console.log(this.state);
if (!(this.state.keyLoaded) ) {
return this.renderLoadingView();
}
return (
<View style={styles.viewContainer} >
<SearchBar onChangeText={(e) => this.clickMovie(e)}> </SearchBar>
<ListView dataSource={this.state.dataSource} renderRow= {this.renderMovie} style={styles.listView}/>
</View>
);
}
exports.tester=function(){
let REQUEST_URL= config.baseUrl + 'api/HotelAdmin/GetKey';
AsyncStorage.getItem('access_token').then((value) => {
fetch(REQUEST_URL, {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + value,
}
}).then((response) => {return response.json()} ).then((responseData) => {
this.setState(
{key: responseData,
keyLoaded: true,
dataSource: this.state.dataSource.cloneWithRows(responseData),
});
}).done();
});
}