如何通过react-adopt动态设置突变变量?

时间:2018-12-23 12:16:57

标签: reactjs graphql react-apollo

在我的组件中,我正在使用react-adopt来组成graphql查询和变异,以使我的渲染道具不会太混乱。我有以下代码:

这是我的变异,它带有一个参数-planID。

const CREATE_ORDER_MUTATION = gql`
  mutation CREATE_ORDER_MUTATION($planID: String!) {
    createOrder(planID: $planID) {
      planID
      name
      description
      subscriptionType
      images
      subscriptionType
      pricePerMonth
}
}

这是take函数,它需要几个突变,其中之一是createOrder。 Apollo的工作方式是我需要在此处将变量prop传递给createOrder组件。问题是,我目前没有planID。 planID仅在实际组件内部可用。

const Composed = adopt({
  toggleCart: <Mutation mutation={TOGGLE_CART_MUTATION} />,
  createOrder: <Mutation mutation={CREATE_ORDER_MUTATION} />,
});

我的组件看起来像这样。我在这里有planID,但是如何将其作为突变的参数传递呢?

render() {
const { plan } = this.props;
return (
  <Composed>
    {({ toggleCart, createOrder }) => {
      const handleAdd = () => {
        toggleCart();
        Router.push('/waschingmachine');
        createOrder();
      };
      return (
        <StyledPlan>
          <h1>{plan.name}</h1>
          <p>{plan.description}</p>
          <img src={`static${plan.images[0]}`} alt="blue1" />
          <h2>{plan.pricePerMonth / 100} EUR</h2>
          <div className="buttons">
            <Link
              href={{
                pathname: '/plan',
                query: { id: plan.id },
              }}
            >
              <button type="button">info</button>
            </Link>
            <button onClick={handleAdd} type="button">
              Select Plan
            </button>
          </div>
        </StyledPlan>
      );
    }}
  </Composed>
);
}

如果无法以这种方式解决它,您将如何以不同的方式来解决?

2 个答案:

答案 0 :(得分:2)

在这里,您可以通过react-adopt方式将参数传递到内部的变异映射器中:

// In a nutshell, `react-adopt` allows you to pass props to your `Composed`
// component, so your inner `mapper` can access those props to pass them to 
// your <Query> or <Mutation>

// Here's your initial `Composed` component from above
const Composed = adopt({
  // `planId` is passed from below via props (see `<ContainerComponent />) 
  toggleCart: ({ planId, render }) => (
    <Mutation mutation={TOGGLE_CART_MUTATION} variables={{ planId }}>{render}</Mutation>,
    ),
  // `planId` is passed from below via props (see `<ContainerComponent />)
  createOrder: ({ planId, render })=> (
    <Mutation mutation={CREATE_ORDER_MUTATION} variables={{ planId }}>{render}</Mutation>                 
  )
});

// `<ContainerComponent />` will take a plan as its props and passed `planId` to 
// the `<Composed />` component
const ContainerComponent = ({ plan }) => (
  <Composed planId={plan.id}>
    {({ toggleCart, createOrder }) => {      
      const handleAdd = e => {
        e.preventDefault();
        toggleCart();
        // ...
        createOrder();
        // ...
      };

      // Whatever your UI needs you can pass them here via here
      return <YourPresentationComponent onClick={handleAdd} />;
    }}
  </Composed>
)

// Now all you need to do is to pass `plan` from your render() to the 
// <ContainerComponent /> (This is the render() where you return your 
render() {
  const { plan } = this.props;
  return <ContainerComponent plan={plan} />
}

希望这对解决您的问题有帮助!只是附带说明,您还可以获取先前的mapper值,并将其作为参数的一部分传递到下一个映射器fn,请参见下文:

const Composed = adopt({ 
  // Here you can retrieve the actual `plan` by using `userId` and pass the result 
  // into your next children mapper fn to consume
  plan: ({ userId, render }) => (
   <Query query={GET_PLAN_GRQPHQL} variables={{ userId }}>{render}</Query>
  ),
  // `plan` is actually coming from above <Query /> component 
  toggleCart: ({ plan, render }) => { //... },
  createOrder: ({ plan, render }) => { //...}
});

答案 1 :(得分:1)

可以通过选项调用在渲染的子代中传递的mutate函数。 选项可以包括在GraphQL突变字符串中使用的变量。 [1]

这意味着您可以像这样调用createOrder变异函数。

createOrder({ variables: { planID: 'some plan id' } });

鉴于planID的动态性质,有多种实现方法。一种方法是使用如下数据属性:

可以在按钮上为计划ID设置data属性。

<button onClick={handleAdd} data-planid={plan.id} type="button">
      Select Plan
</button>

handleAdd可以重构,以从目标数据集属性中获取planid并使用createOrder变量调用planID

const handleAdd = event => {
    const planID = event.target.dataset.planid;
    toggleCart();
    Router.push('/waschingmachine');
    createOrder({ variables: { planID } });
};

另一种方法是在planID属性的按钮中调用handleAdd并将其直接传递给onClick

<button onClick={() => handleAdd(plan.id)} type="button">
      Select Plan
</button>

然后更新处理程序

const handleAdd = planID => {
    toggleCart();
    Router.push('/waschingmachine');
    createOrder({ variables: { planID } });
};

两种方法都需要权衡。对于较早的方法,将planid在DOM中设置为属性,以后可以读取。 对于下一个,为N个计划创建N个处理程序,并将其保存在内存中。