在NextJs中如何使用change事件更改getServerSideProps

时间:2020-09-27 09:22:13

标签: javascript reactjs fetch next.js getserversideprops

在这里,我试图根据类别更改产品数据, 我有一个索引页和两个分别名为ProductsCategories的组件。首先,我要按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的新手,所以我不知道该怎么做,我将不胜感激任何建议/建议

1 个答案:

答案 0 :(得分:0)

使用getServerSideProps函数时数据是否是您想要的?

我在catProducts中可以做的是URL中没有'/ api',而在getServerSideProps中有'/ api'。这可能是原因之一。

也请在使用访存时保证。

相关问题