constructor(props){
super(props);
this.state = {
services:
[
{
"name": "",
"icon": require('./home-icon1.png')
},
{
"name": "",
"icon": require('./home-icon2.png')
},
{
"name": "",
"icon": require('./home-icon3.png')
},
{
"name": "",
"icon": require('./home-icon4.png')
},
]
};
}
componentWillMount(){
fetch('link.com', {
method: 'GET',
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson.message === "List of Services"){
var length = responseJson.result.length.toString();
ToastAndroid.show(responseJson.message, ToastAndroid.LONG);
for(var i = 0 ; i < length ; i++){
const services = [...this.state.services];
services[i].name = responseJson.result[i].Service.service_name
this.setState({ services : services });
//this.setState({[services[i].name] : responseJson.result[0].Service.service_name})
}
Alert.alert(services.length);
}
else{
Alert.alert("Cant Connect toSErber");
}
}).catch((error) => {
console.error(error);
});
}
基本上我想做的是从服务器获取一些数据,然后使用该数据更改服务状态(即组件状态),但是我用来为服务设置状态的语法是错误的。从服务器获取数据后,我正确设置了服务状态
答案 0 :(得分:0)
您过度设计了它。试试这个:
在获取数据时,请执行以下操作:
const services = [... this.state.services]; const serviceData = responseJson.result;
serviceData.map((service,index)=> { services [index] ['name'] = service.Service.service_name; services [index] ['icon'] = iconComponent; });
this.setState({services});