【问题标题】:In NextJs how to change getServerSideProps with change event在 NextJs 中如何使用更改事件更改 getServerSideProps
【发布时间】:2021-01-13 03:10:14
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs fetch next.js getserversideprops


    【解决方案1】:

    使用getServerSideProps函数时传入的数据是你想要的吗??

    我可以在 catProducts 中看到 URL 中没有“/api”,而在 getServerSideProps 中有“/api”。这可能是原因之一。

    还请在使用 fetch 时承诺。

    【讨论】:

    • api没问题,我把实际的api url改成了dummy url
    • 尝试使用 promise 和 console.log(error)。还要检查网络选项卡,看看是否正在拨打电话,如果拨打电话而不是响应。
    • 还有一点,'cat_id' 来自哪里??这也可能是一个原因,因为您点击的网址可能需要 cat_id 但未定义发送。
    • 它来自类别组件,cat id 没问题,我已经记录了,cat_id 和 api 链接没有问题,我想我试图用错误的方法这样做
    猜你喜欢
    • 2021-08-10
    • 2020-05-14
    • 1970-01-01
    • 2021-11-13
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多