如何解决使用表单中的选择值作为API参数来获取响应-Reactjs
我正在尝试从表单中获取选定的下拉值,并将其作为参数传递给API以显示所需的详细信息。
function Form() {
let productID = [];
let viewID = [];
for (let i = 1; i <= 20; i++) {
productID.push(i);
}
for (let j = 1; j <= 10; j++) {
viewID.push(j);
}
const [ selectProduct,setSelectProduct ] = useState('');
const [ selectView,setSelectView ] = useState('');
const [ state,setState] = useState({
isSubmitted: false
})
function handleChange(e) {
let selectProd = e.target.value;
setSelectProduct(selectProd);
}
function handleChangeView(e) {
let selectVal = e.target.value;
setSelectView(selectVal);
}
function handleSubmit(e) {
e.preventDefault()
setState({isSubmitted: true})
}
return (
<div>
<h1 className="heading">Product Review Page</h1>
<h4 className="subheading"> Check your Product's Review</h4>
{/* Product ID */}
<form onSubmit={handleSubmit}>
<div className="form">
<div className="prod">
<label className="name">
Choose the Product ID{" "}
<span className="num">[between 1- 20]</span>:{" "}
</label>
<select
name="prod"
onChange={handleChange}
value={selectProduct}
>
{productID.map((num) => {
return (
<Input
key={num}
name="productID"
val={num}
/>
);
})}
</select>
</div>
<div>
{/* View ID */}
<label className="name">
Choose the Viewer ID{" "}
<span className="num">[between 1- 10]</span>:{" "}
</label>
<select
name="viewer"
onChange={handleChangeView}
value={selectView}
>
{viewID.map((num) => {
return (
<Input
key={num}
name="viewerID"
val={num}
/>
);
})}
</select>
</div>
</div>
<input className="button" type="submit" value="submit" />
</form>
{ state.isSubmitted && <ProductPage product={selectProduct} viewer={selectView} /> }
</div>
);
输入是创建选项的组件。
我只需要在提交后保存选择值,而不是每个onChange,以便在API中仅使用提交的值来获取响应
function ProductPage(props) {
const [ products,setProducts ] = useState({});
let URL = `${baseURL}${props.product}/${props.viewer}`;
useEffect(() => {
async function api() {
try {
const response = await fetch(URL);
return await response.json();
} catch (error) {
return console.log("Error :",error);
}
}
api()
.then((data) => setProducts(data))
.catch((error) => alert("Couldn't load data"));
},[URL]);
console.log(products);
return (
<div>
<Product data={products}/>
</div>
)
}
但是第一个响应为空,因此不能使用该值,以后再使用它的前一个响应和新的响应。
function Product(props) {
console.log("data" + props.data);
return (
<div className="prodPage">
<h4> Product Review</h4>
<div className="content">
<ul>
{/* <li>
{props.data.reviews[0].friend === true &&
`Name : ${props.data.reviews[0].reviewer.name}`}
</li>
<li>`Comment: ${props.data.reviews[0].comment} `</li> */}
</ul>
</div>
</div>
);
}
请帮助我解决此问题
响应的屏幕截图,
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。