你好,我刚开始学习react。我有一个文本字段和一个按钮。然后单击按钮,我通过调用graphql显示一些结果(使用其他功能组件作为结果)。但是在这里我面临的问题是按钮仅工作一次,之后单击按钮就无法再次调用graphql api。我怀疑仅showResults布尔变量存在一些问题(我在单击按钮时设置了此问题)。有人可以帮我找出问题。
const [consumption, setConsumption] = React.useState(1500);
const [showResults, setShowResults] = useState(false);
const displayProducts = () => {
setShowResults(true);
};
const handleConsumptionChange = (event) => {
let consumptionEntered = event.target.value;
setConsumption(consumptionEntered);
};
return (
<div className="simple">
<TextField
label="Kwh"
size="medium"
value={consumption}
onChange={handleConsumptionChange}
variant="outlined"
/>
<Button variant="contained" size="medium"
onClick={displayProducts}>Tarif finden</Button>
{showResults && <ProductResults/>}
</div>
);
};
export default SimpleForm;
' And my results display functional component code is below'
const ProductResults = (props) => {
let bookId = props.bookId;
const GET_BOOK = gql`
{
bookById(id: "book-1") {
id
name
pageCount
author{
id
firstName
lastName
}
}
}
`;
console.log("props set is ::{}", props.bookId);
const {loading, error, data} = useQuery(GET_BOOK);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error :(</div>;
return (
<div className="Product Results">
<dl>
<dd><span>{data.bookById.id}</span></dd>
<dd><span>{data.bookById.name}</span></dd>
<dd><span>{data.bookById.pageCount}</span></dd>
<dd>
<h4>author details</h4>
<ul>
<li>Author Id: {data.bookById.author.id}</li>
<li>First Name: {data.bookById.author.firstName}</li>
<li>Last Name: {data.bookById.author.lastName}</li>
</ul>
</dd>
</dl>
</div>
);
};
export default ProductResults```
答案 0 :(得分:0)
每次单击按钮时,它可能都会调用,但是单击按钮只会调用设置了displayProducts
的{{1}}。
您可以使用setShowResults(true)
将其转换为切换按钮,或者需要向setShowResults(previous => !previous)
组件添加单独的“刷新”按钮/功能。
答案 1 :(得分:0)
一旦状态设置为“ true”,则始终将其设置为true。因此,我猜没有状态更改和更新。在setConsumption之后尝试setShowResults(false)