我目前正在尝试找出如何通过将用户通过表单提交的文本数据用作返回结果数组的查询中的变量参数来实现搜索功能的方法。 AssetQueryInit查询的结果很好。 (AssetQueryInit只是呈现硬编码查询的结果)
我是新手,我们将不胜感激!
GraphQL服务器
const typeDefs = `
type Asset {
_id: ID
assetName: String
headline: String
language: String
sentimentNegative: Float
sentimentNeutral: Float
sentimentPositive: Float
firstCreated: String
}
type Query {
asset(assetName: String!): Asset
assetAll(assetName: String!): [Asset]
}
`;
const resolvers = {
Query: {
asset: (_,{assetName})=> Asset.findOne({assetName : assetName }),
assetAll: (_,{assetName}) => Asset.find({assetName: assetName})
}
};
const server = new GraphQLServer({ typeDefs, resolvers });
反应
const AssetAllQuery = gql`
{
assetAll(assetName: $text){
_id
assetName
headline
firstCreated
sentimentNegative
sentimentPositive
sentimentNeutral
}
}
`;
class App extends Component {
assetAll = async (text) =>{
await this.props.assetAll({
variables:{
assetName: text
},
update:(store,{data: {assetAll}}) => {
const data = store.readQuery({query: AssetAllQuery});
data.assetAll.unshift(assetAll);
}
});
};
render() {
const {
data : { loading, assetAll }
} = this.props;
console.log("test");
if(loading){
return null;
}
return (
<div className="App">
<Form submit ={this.getAllAssets}/>
{assetAll.map(Asset => <div key={Asset._id}>{Asset.headline} | {Asset.sentimentNeutral > Asset.sentimentPositive ? (Asset.sentimentNeutral > Asset.sentimentNegative ? "Neutral" : "Sell") : "Buy"} </div>)}
</div>
);
}
};
export default compose(
graphql(AssetAllQuery, {name: "assetAll"}),
graphql(AssetQueryInit)
)(App);
输出
[GraphQL error]: Message: Variable "$text" is not defined., Location: [object Object],[object Object], Path: undefined bundle.js:837:32
[Network error]: Error: Response not successful: Received status code 400
答案 0 :(得分:1)
在查询中,基本上必须将您使用的任何$variables
都声明为整个事物的输入参数:
const AssetAllQuery = gql`
AssetAll($assetName: String!) {
assetAll(assetName: $assetName){
...
}
}
`;
顶级操作名称并不重要; $variable
有自己的声明类型,必须与查询主体中使用的类型匹配;并且在进行查询时,variables:
的名称必须与声明的查询参数的名称匹配。