因此,我正在使用本地状态来切换打开/关闭窗口,这是通过onClick事件来完成的。但是我通过componentDidMount()触发了相同的功能,但无法正常工作。
我的代码如下:
Resolver:
clientState: {
resolvers: {
Mutation: {
toggleCart(_, variables, { cache }) {
// read the cartOpen value from the cache
const { cartOpen } = cache.readQuery({
query: LOCAL_STATE_QUERY,
});
// Write the cart State to the opposite
const data = {
data: { cartOpen: !cartOpen },
};
cache.writeData(data);
return data;
},
},
},
defaults: {
cartOpen: false,
},
},
Queries:
const LOCAL_STATE_QUERY = gql`
query {
cartOpen @client
}
`;
const TOGGLE_CART_MUTATION = gql`
mutation {
toggleCart @client
}
`;
Components:
<Mutation mutation={TOGGLE_CART_MUTATION}>
{(toggleCart) => {
return (
<Mutation
mutation={UPDATE_ITEM_MUTATION}
variables={{
id: this.props.itemid,
quantity: itemDetails.quantity - this.props.quantity,
}}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{(updateItem, { loading, error }) => (
<>
<MutationOnMount mutation={toggleCart} />
<MutationOnMount mutation={updateItem} />
</>
)
}
</Mutation>
);
}}
</Mutation>
class MutationOnMount extends React.Component {
componentDidMount() {
this.props.mutation(); // Run mutation on Mount
}
render() {
return (
null
);
}
}
照原样,通过componentDidMount()触发突变不会产生预期的结果,但是如果我替换
<MutationOnMount mutation={toggleCart} />
with
<div><button type="button" id="toggleCartButton" disabled={loading} onClick={toggleCart} /></div>
然后,当我单击按钮时,该突变工作正常。有什么想法为什么不能通过componentDidMount()工作?