有谁知道向 apollo 添加查询变量的正确方法是如何从 React 中获得的?如果我手动添加书名字符串而不是传入 $name
查询变量,我可以让以下代码正常工作,但是一旦我添加它并尝试通过propTypes 中的选项,不变违规:包装“BookPage”的操作“data”需要一个变量:“name”,但在传递给“Apollo(BookPage)”的 props 中找不到该变量
我直接从reactQL中提取了装饰器的语法。包,所以我知道它比其他示例有更多的语法糖,但它对于查询应该仍然有效,对吗?
const query = gql`
query ($name: String!){
bookByName(name: $name) {
id
}
}
`;
@graphql(query)
class BookPage extends React.PureComponent {
static propTypes = {
options: (props) => { return { variables: { name: "Quantum Mechanics"}}},
data: mergeData({
book:
PropTypes.shape({
id: PropTypes.string.isRequired,
}),
}),
}
render() {
const { data } = this.props;
if (data.loading) {
return <p>Loading</p>
}
const { bookByName } = data;
const book = bookByName;
return (
<p>book.id</p>
);
}
}
export default BookPage;
最佳答案
@graphql
装饰器有第二个参数,您可以在其中定义查询或突变的选项。
类似于 config 中的选项定义.
所以在你的情况下它可能看起来像:
const query = gql`
query ($name: String!){
bookByName(name: $name) {
id
}
}
`;
@graphql(query, {
options: (ownProps) => ({
variables: {
name: ownProps.bookName // ownProps are the props that are added from the parent component
},
})})
class BookPage extends React.PureComponent {
static propTypes = {
bookName: PropTypes.string.isRequired,
data: mergeData({
book:
PropTypes.shape({
id: PropTypes.string.isRequired,
}),
}),
}
render() {
const { data } = this.props;
if (data.loading) {
return <p>Loading</p>
}
const { bookByName } = data;
const book = bookByName;
return (
<p>book.id</p>
);
}
}
export default BookPage;
关于reactjs - 如何将 graphQL 查询变量传递到装饰的 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44252916/