React Native无法渲染GraphQL服务器查询数据,求排查解决
问题分析与解决
你的核心问题是直接将JavaScript对象传递给React Native的<Text>组件,React Native无法渲染原始对象,所以看不到数据。虽然你在控制台用JSON.stringify能正常打印,但渲染时没做相同处理,也没有遍历数组展示具体内容。
修复方案
方案1:快速验证(查看完整数据结构)
将data转为字符串后渲染,和你控制台打印的方式一致:
return ( <View> <Text>{JSON.stringify(data, null, 2)}</Text> </View> );
方案2:正确渲染用户列表(推荐)
getAllUsers返回的是用户数组,你需要遍历数组,逐个渲染每个用户的信息(注意:不要在UI上展示密码,这是安全风险):
return ( <View style={{alignItems: 'center'}}> <Text>用户列表:</Text> {data.getAllUsers.map(user => ( <View key={user.id} style={{marginTop: 10, padding: 10, borderWidth: 1, borderColor: '#ccc'}}> <Text>ID: {user.id}</Text> <Text>用户名: {user.userName}</Text> </View> ))} </View> );
完整修改后的GettAllUsers组件
function GettAllUsers() { console.log("this is being executed") return ( <Query query={GET_USERS}> {({ loading, error, data }) => { if (loading){ console.log(loading) return( <View> <Text>loading</Text> </View> ) } if (error){ console.log(error) return ( <View> <Text>error</Text> </View> ) } Object.keys(data).forEach(key => { console.log(JSON.stringify(key) + JSON.stringify(data[key])); }); return ( <View style={{alignItems: 'center'}}> <Text>用户列表:</Text> {data.getAllUsers.map(user => ( <View key={user.id} style={{marginTop: 10, padding: 10, borderWidth: 1, borderColor: '#ccc'}}> <Text>ID: {user.id}</Text> <Text>用户名: {user.userName}</Text> </View> ))} </View> ); }} </Query> ); }
内容的提问来源于stack exchange,提问作者Fabricio la Torre
相关产品推荐
相关产品推荐

