在这里,我试图根据类别更改产品数据,我有一个索引页面和两个名为Products
and的组件Categories
。起初我正在获取所有产品,getServerSideProps
然后当用户选择一个类别时我需要获取类别明智的产品。
索引页
import Link from 'next/link';
import Layout from '../components/layouts/App';
import Products from '../components/Products';
import Categories from '../components/Categories';
class Index extends React.Component {
state={
products:this.props.products,
}
//receiving category id and trying to change state products
catProducts = async (cat_id) => {
const res = await fetch(`https://example.com/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699&category_id=${cat_id}`, { method: 'GET' })
const productsdata =await res.json()
console.log(productsdata)
// this.setState({products: productsdata})
}
render() {
return (
<div>
<Layout>
<div className="main-wrapper pt-35">
<div className="row">
<div className="col-lg-3">
<Categories categories={this.props.categories} catchange={this.catProducts}/>
</div>
<div className="col-lg-9 order-first order-lg-last">
<Products products={this.state.products} />
</div>
</div>
</div>
</Layout>
</div>
)
}
}
export async function getServerSideProps() {
const cats_req = await fetch('https://example.com/api/get_categories?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699', { method: 'POST' })
const categories = await cats_req.json();
const products_req = await fetch(`https://example.com/api/get_products?api_key=4e38d8be3269aa17280d0468b89caa4c7d39a699`, { method: 'GET' })
const products = await products_req.json();
return {
props: {
products: products,
categories: categories
}
}
}
export default Index
在这里我收到一个错误Unhandled Runtime Error TypeError: Failed to fetch
我是下一个 js 的新手,所以我不知道该怎么做,我将不胜感激任何建议/建议