这里我试图根据类别更改产品数据,我有一个索引页和两个名为Products
和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的新手,所以我不知道如何做到这一点,我会感谢的任何建议
使用getServerSideProps函数时收到的数据是您想要的吗??
我在catProducts中所能做的是URL中没有"/api",而在getServerSideProps中有"/api"。这可能是原因之一。
另外,请在使用fetch时承诺。