我正在使用react-apollo
与react-native-gifted-chat
结合使用。
我正在尝试从用户那里获取输入并将其传递给我的this.props.addMessageToTeam
方法。
我在将输入值传递给graphql
突变时遇到困难。这是graphql变异部分的样子:
const addMessageToTeam = gql`
mutation {
createMessage(
message: $message,
teamId: "21345667"
) {
id
message
}
}
`;
请参阅以下完整代码:
import React, { Component } from 'react';
import { View } from 'react-native';
import { GiftedChat, Bubble } from 'react-native-gifted-chat';
import styled from 'styled-components/native';
import gql from 'graphql-tag';
import { graphql, compose } from 'react-apollo';
class Chat extends Component {
state = {
message: '',
messages: [],
}
updateText = (e) => {
this.setState({
message: e
});
}
renderBubble (props) {
return (
<Bubble {...props} />
);
}
sendMessage = (e) => {
this.props.addMessageToTeam(e[0].text);
}
render() {
let allMessages = this.props.data.allMessages || [];
allMessages = allMessages.map(msg => {
return {
_id: msg.id,
text: msg.message,
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://facebook.github.io/react/img/logo_og.png',
}
}
});
return (
<MainContainer>
<GiftedChat
messages={ allMessages }
renderBubble={this.renderBubble}
onInputTextChanged={this.updateText}
onSend={this.sendMessage}
user={{ _id: 12345 }}
/>
</MainContainer>
);
}
}
const MainContainer = styled.View`
display: flex;
flex: 1;
`
const getAllMessages = gql`
query {
allMessages {
id
message
}
}
`;
const addMessageToTeam = gql`
mutation {
createMessage(
message: $message,
teamId: "21345667"
) {
id
message
}
}
`;
export default compose(
graphql(getAllMessages),
graphql(addMessageToTeam, { name: 'addMessageToTeam' }),
)(Chat);
如果需要任何进一步的信息,请告诉我。
答案 0 :(得分:1)
在您提供的场景中,应使用遵循以下结构的对象调用变异:
sendMessage = (e) => {
this.props.addMessageToTeam({
variables: {
message: e[0].text,
}
});
}
这是因为graphql变异是用一个名为$message
您还应该将graphql声明更改为:
mutation CreateMessage($message: String) {
createMessage(message: $message, teamId: "21345667")
}