#reactjs #graphql #react-apollo
#reactjs #graphql #реагировать-apollo
Вопрос:
Если я сохраню свои кнопки в своем дочернем элементе, это отлично работает, за исключением того факта, что у меня есть кнопки, отображаемые в каждой строке. Я бы хотел переместить свои кнопки в родительский элемент, чтобы они отображались только один раз в нижней части экрана. Я попытался переместить свои кнопки на возврат родительского элемента и поместить свой код состояния над возвратом. Я думаю, это сработало бы, за исключением того, что мое значение «count» в моем дочернем элементе для моей переменной graphql «offset» теперь нуждается в доступе к «count» в моем родительском элементе. Не уверен, как это сделать. Я довольно новичок в react и graphql.
import React, { Component, useState } from 'react';
import { useQuery, gql } from '@apollo/client';
import {Table, Spinner, Button} from 'react-bootstrap'
const Customer_List = gql`
query getCust ($configID: Int, $first: Int, $offset: Int ) {
docsconfig (configID:$configID first:$first offset:$offset) {
SubDomain
ConfigID
CustID
customers {
FirstName
LastName
}
}
}
`
function CustomerList() {
const { loading, error, data} = useQuery(Customer_List, {
variables: {
configID: 1436,
first: 10,
offset: count
},
}
);
if (loading) return <td> <Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner> </td>
if (error) return <p>Error :(</p>;
return data.docsconfig.map(({ CustID, SubDomain, customers, FirstName, LastName}) => (
<tr key={CustID}>
<td>{customers.FirstName}</td>
<td>{customers.LastName}</td>
<td>{SubDomain}</td>
</tr>
)
)
}
function Customers () {
const [count, setCount] = useState(0)
function increase() {
setCount(count 10);
}
function decrease() {
setCount(count - 10);
if (count === 0) {
setCount(count 0);
}
}
return (
<Table striped bordered hover>
<thead >
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>SubDomain</th>
</tr>
</thead>
<tbody>
<CustomerList />
</tbody>
<tr>
<button onClick={decrease}>-</button>
<button onClick={increase}> </button>
</tr>
</Table>
);
}
export default Customers;
Ответ №1:
Передать count
в качестве реквизита CustomerList
.
Список клиентов
function CustomerList({ count }) { // <-- desctructure count from props
const { loading, error, data} = useQuery(
Customer_List,
{
variables: {
configID: 1436,
first: 10,
offset: count // <-- pass to config/options
},
}
);
...
Клиенты
function Customers () {
const [count, setCount] = useState(0)
...
return (
<Table striped bordered hover>
<thead >
...
</thead>
<tbody>
<CustomerList count={count} /> // <-- pass count to CustomerList
</tbody>
<tr>
<button onClick={decrease}>-</button>
<button onClick={increase}> </button>
</tr>
</Table>
);
}
Комментарии:
1. Спасибо!!! Теперь он работает! Я потратил так много часов, пытаясь получить доступ к этому значению. Похоже, мне нужно потратить еще немного времени на понимание реквизита. Еще раз спасибо!!!
2. @montman Отлично! IMO документы react очень хорошо объясняют большинство аспектов React и, конечно же, как работать с состоянием и реквизитами. Добро пожаловать в React и добро пожаловать в SO. Приветствия.