我有一个后端 Drupal 站点和 React-native 应用程序作为我的前端。我正在从应用程序执行 graphQL 查询,并且能够在 console.log
中显示内容。但是,我的目标是使用在渲染返回方法内查询的调用并将其显示在应用程序中,但没有运气。请注意,我有另一个 REST API 调用 testName
并且已显示在应用程序中。我主要关心的是如何在应用程序中显示 graphQL 查询。
下面是我的实际实现,但删除了一些行。
...
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'http://192.168.254.105:8080/graphql'
});
client.query({
query: gql`
query {
paragraphQuery {
count
entities {
entityId
...on ParagraphTradingPlatform {
fieldName
fieldAddress
}
}
}
}
`,
})
.then(data => {
console.log('dataQuery', data.data.paragraphQuery.entities) // Successfully display query contents in web console log
})
.catch(error => console.error(error));
const testRow = ({
testName = '', dataQuery // dataQuery im trying to display in the app
}) => (
<View>
<View>
<Text>{testName}</Text> // This is another REST api call.
</View>
<View>
<Text>{dataQuery}</Text>
</View>
</View>
)
testRow.propTypes = {
testName: PropTypes.string
}
class _TestSubscription extends Component {
...
render () {
return (
<View>
<FlatList
data={this.props.testList}
...
renderItem={
({ item }) => (
<testRow
testName={item.field_testNameX[0].value}
dataQuery={this.props.data.data.paragraphQuery.entities.map((dataQuery) => <key={dataQuery.entityId}>{dataQuery})} // Here I want to call the query contents but not sure how to do it
/>
)}
/>
</View>
)
}
}
const mapStateToProps = (state, ownProps) => {
return ({
testList: state.test && state.test.items,
PreferredTest: state.test && state.test.PreferredTest
})
}
...
最佳答案
那里有一些不同的地方是错误的。
Syntax error
是因为你的<key>
此处标签未正确关闭:(dataQuery) => <key={dataQuery.entityId}>{dataQuery})
而且...没有
<key>
React Native 的元素。您可以查看docs Components部分支持哪些组件。顺便说一句,React 也没有这样的元素。请求数据是异步的。因此,当您在
render()
中发送请求时此方法在返回数据之前更早完成执行。你就是不能那样做。你能做什么呢?您应该请求数据(在此元素或其父元素或 Redux reducer 中 - 没关系),在获得结果后,您需要使用.setState
设置状态(如果它发生在组件内部)或.dispatch
(如果您使用的是 Redux)。这将调用render()
并且组件将使用检索到的数据进行更新。还有一个关于显示微调器或使用其他方法让用户知道数据仍在加载的问题。但这是正交问题。只是为了让您知道。即使请求数据以某种方式同步(例如从 LocalStorage 读取数据),您也绝不能在
render()
中执行此操作.此方法的调用频率比您预期的要高得多,因此在此添加任何重载将导致性能显着下降。
因此,考虑到 #3 和 #4,您应该在 componentDidMount()
中运行数据加载/获取, componentDidUpdate()
或者作为处理按钮点击的一部分。
关于javascript - 在返回方法中访问查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53041685/