reactjs - axios发布请求后未设置状态数组
问题描述
我有一个名为 数组的状态contacts
,然后我向我的服务器(即我的后端)发出 axios 发布请求,然后我尝试使用从服务器获得的响应设置数组(联系人)并将其显示在平面列表中,但它总是会带来一个错误,说undefined is not an object (evaluating 'item.receiver.first_name')
这意味着数组没有按预期设置,请问我做错了什么
AXIOS 请求
componentDidMount() {
const {params} = this.props.navigation.state;
contact_id = 18;
if(contact_id){
console.log("mmm");
console.log(contact_id);
console.log("mmm");
this.setState({loading: true});
var bodyParameters = {
id: contact_id,
}
/* var config = {
headers: {'Authorization': "Bearer " + this.state.token}
};*/
axios.post(
'http://10.0.2.2:8000/api/contacts',
bodyParameters,
// config
).then((response) => {
this.setState({loading: false});
console.log(response);
var len = response.data.success.length;
for (let i = 0; i < len; i++) {
let row = response.data.success;
console.log(row);console.log(i);console.log("djdn")
this.setState(prevState => ({
contacts: [...prevState.contacts, row],
}), console.log(this.state.contacts));
};
}).catch((error) => {
this.setState({loading: false});
Alert.alert(
'Error',
'Internal Server Error, please try again later',
[
{text: 'OK'},
], );
console.log(error);
});
}
}.bind(this), 100);
}
来自服务器的响应
{ data:
{ success:
[ { id: 1,
sender_id: 18,
receiver_id: 3,
last_message:
{ id: 1,
message: 'books and books bro, no fear',
created_at: '2018-09-05 09:13:01',
updated_at: '2018-09-05 09:13:01',
read: 0,
sent: 0,
user1: 3,
user2: 18 },
created_at: null,
updated_at: null,
receiver:
{ id: 3,
user_name: 'Leke',
email: 'leke@sele.com.ng',
first_name: 'Leke',
last_name: 'Doe',
phone_no: '08109823438',
image_url: null,
birthday: '02/05/2030',
gender: 'male',
servicer: 1,
rating: '5.0',
school_id: 21,
created_at: '2018-09-05 09:13:01',
updated_at: '2018-09-12 14:44:40',
provider: null,
provider_id: null,
job_title: null,
profile_description: null } },
{ id: 2,
sender_id: 18,
receiver_id: 1,
last_message:
{ id: 4,
message: 'everything stew',
created_at: '2018-09-05 09:13:02',
updated_at: '2018-09-05 09:13:03',
read: 0,
sent: 0,
user1: 1,
user2: 18 },
created_at: null,
updated_at: null,
receiver:
{ id: 1,
user_name: 'Jane',
email: 'jane@sele.com.ng',
first_name: 'Jane',
last_name: 'Doe',
phone_no: '08109823487',
image_url: null,
birthday: '19/08/2018',
gender: 'female',
servicer: 1,
rating: '3.0',
school_id: 35,
created_at: '2018-09-05 09:13:01',
updated_at: '2018-09-05 09:13:01',
provider: null,
provider_id: null,
job_title: null,
profile_description: null } } ] },
状态和扁平化清单
constructor(props) {
this.state = {
contacts: [],
};
}
const contacts = (
<FlatList
data={this.state.contacts}
renderItem={({ item }) => (
<TouchableNativeFeedback
onPress={() =>
this.props.navigation.navigate('Chat', {}
)}>
<View style={styles.chats}>
<View style={styles.profiles}>
<Image resizeMode="contain" style={{alignSelf: 'center', flex: 1,}}
source={require('../teeth.png')}/>
</View>
<View style={styles.chatTexts}>
<Text style={styles.profileName}>
{item.receiver.first_name} {item.receiver.last_name}
{'\n'}{'\n'}
{item.last_message.read?<Text style={{fontSize: 12}}>
{item.last_message.message}
</Text>:<Text style={{fontSize: 12, color: '#ADA5A5'}}>
{item.last_message.message}
</Text>}
</Text>
</View>
<Text style={{fontSize: 12,
position: 'absolute',
right: '8.33%',fontFamily: 'mont-medium',
color: '#000',
textAlign: 'left',
marginTop: 14,}}>
12:15
</Text>
</View>
</TouchableNativeFeedback>
)}
keyExtractor={item => item.id}
/> );
错误
TypeError: undefined is not an object (evaluating 'item.receiver.first_name')
解决方案
在componentDidMount
方法之后调用生命周期方法render
,如果我们在其中设置状态,componentDidMount
那么它将重新渲染组件。
所以你需要添加一个空检查,item
因为当第一次执行渲染方法时,contacts
状态是一个空数组。因此,它会抛出错误。
推荐阅读
- discord.py - discord.py Selfbot 无法获取公会用户
- angular - Vidyo.io 远程 JS 不可用
- python - 拖放移动时的选择问题,PyQt5
- docker - Docker 本地卷驱动程序选项
- c# - 尝试通过 C# Interop 保存只读 Excel 文件时出错
- python - 在 Python 中操作 URI
- c - 即使在手动释放内存后,valgrind 也会显示内存泄漏
- python - 使用 pyyaml 序列化自定义类
- ios - Camera.app 使用什么 AVCaptureDevice?
- weka - Weka 异常:训练和测试文件不兼容!尽管有可以纠正这种不兼容性的过滤器,但还是抛出了