我从我的API获得一个大小,该大小适用于邮递员,也适用于该应用程序。我将其分配给我的尺寸状态,如果我写console.warn(this.state.size)
,将出现一个空警告,这表示此尺寸为空;如果我写console.error(this.state.size)
,则将出现数字2,即答案。
我只是想从API分配一些变量,但是如果我将它们声明为状态,则会在状态上产生问题循环,因此我将它们设置为全局数组。我不知道是什么引起了问题,但是从0到大小的loadnum
将从1到2。
UNSAFE_componentWillMount() {
this.setState({loading : true});
fetch(API_URL + '/auth/getsize', {
method: 'GET',
headers: {
Accept: 'application/json',
'Authorization' : 'Bearer ' + window._token,
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({loading : false});
response = ""+responseJson.message;
if(response == "Unauthenticated."){
console.warn(responseJson.message);
}else {
this.setState({size : responseJson.size}, function () {console.error(responseJson.size)});
}
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => {
this.props.navigation.openDrawer()}}
>
<Icon name="menu" />
</Button>
</Left>
<Body style = {{
justifyContent: "flex-end",
alignItems: "flex-end"}}>
<Title>صفحه اصلی</Title>
</Body>
</Header>
<Content>
<ListView enableEmptySections={true} dataSource={
new ListView.DataSource(
{
rowHasChanged: (r1, r2) => r1 !== r2
}
).cloneWithRows(global.num)}
renderRow={
(rowData) =>
<ListItem avatar>
<Left>
<Thumbnail source={require('../img/avatar.jpg')} />
</Left>
<Body>
<Text>{global.title[rowData-1]}</Text>
<Text note>{global.author[rowData-1]}</Text>
</Body>
<Right>
<Text note>1:06 pm</Text>
</Right>
</ListItem>
} />
</Content>
<Button style = {{marginBottom : 5}}onPress={()=>{
this.fetchContent();
}}>
<Icon name ="refresh"/>
</Button>
</Container>
);
} }
export default class ListAvatarExample extends Component {
constructor(props) {
super(props);
this.state = {size:0 ,loading : false};
global.title = [];
global.num = [];
global.data = [];
global.author = [];
global.imageurl = [];
}
loadnum = 0;
addNum(id){
global.num.push(id);
}
addTitle(newTitle) {
global.title.push(newTitle);
}
addAuthor(newAuthor) {
global.author.push(newAuthor);
}
addData(newData) {
global.data.push(newData);
}
addImgurl(newImgurl) {
global.imageurl.push(newImgurl);
}
fetchContent() {
this.setState({size :2}, function () {
for(this.loadnum ; this.loadnum < this.state.size; this.loadnum++)
{
fetch(API_URL + '/auth/getcontent/' + this.loadnum, {
method: 'GET',
headers: {
Accept: 'application/json',
'Authorization' : 'Bearer ' + window._token,
},
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({loading : false});
response = ""+responseJson.message;
if(response == "Unauthenticated."){
console.warn(responseJson.message);
}else {
this.addNum(this.loadnum);
this.addTitle(responseJson.title);
this.addAuthor(responseJson.author);
this.addData(responseJson.data);
this.addImgurl(responseJson.imageurl);
}
})
.catch((error) => {
console.error(error);
});
}
console.warn(JSON.stringify(global.title));
console.warn(this.loadnum)
this.setState({ loading : !this.state.loading});
});
}