不变违规:无效的挂接调用。挂钩只能在功能组件的主体内部调用

时间:2019-08-12 15:41:40

标签: reactjs react-hooks

因此,我从onClick事件调用钩子突变(toggleCartClose)后收到上述错误,需要在触发onClick事件(SickButton)时对其进行操作。我该如何解决?

注意:如果我在onClick事件中删除了signIn();调用,那么错误就消失了。

const signIn = props => {
  Router.push({
    pathname: '/signup',
    query: { fromCart: 'true' }
  })
};

const Cart = props => {

  const { data: dataQuery, error: errorQuery, loading: loadingQuery } = useQuery(
    LOCAL_STATE_QUERY,
  );

  const [ toggleCartClose ] = useMutation(
    TOGGLE_CART_CLOSE_MUTATION,
  );

  const [ toggleCart ] = useMutation(
    TOGGLE_CART_MUTATION,
  );

  return (
    <User>
      {({ data: { me }, loading, error }) => {
        ...
        return (
          <CartStyles open={dataQuery.cartOpen}>
            <header>
            ...
            <footer>
              <table width="100%" border="0">
                <tbody>
                <tr>
                  <td colSpan="2">
                  <div>
                    <SickButton loggedout disabled={loading} onClick={() => {alert('Please....'); signIn(); toggleCartClose()}} background={loading ? props => props.theme.grey : props => props.theme.blue}>Checkout</SickButton>
                  </div>                
                  </td>
                </tr>
                </tbody>
              </table>
          </footer>
          </CartStyles>
        );
      }}
    </User>
  )
};

1 个答案:

答案 0 :(得分:0)

因此我通过将变异钩子调用移至被调用的路由来解决此问题:

signup.js

  const [ toggleCartClose ] = useMutation(
    TOGGLE_CART_CLOSE_MUTATION,
  );

  useEffect(() => {
    if (fromCart) {
      toggleCartClose();
    }
  }, [urlReferer]);