Initially fetch data and pass props to another component

旧时模样 提交于 2020-03-05 03:13:08

问题


I have honestly (and perhaps ashamedly) been flummoxed by this for well over a week now. I've read the Next.js documentation back to front and have scoured the web for hours. I am clearly missing something and would appreciate it if someone could take a look.

When Index.js gets loaded, it sends a request to my database (via) express and this returns a json response. The intention is for my ProductList component to .map() this response - which has been passed to it via props - into my individual products.

With the below code, I can get my index.js to render the products when I initially load another page and then link to it client side. However, I can't get Index.js to load my products if I initially load this page.

[Json views][1] [1]: https://i.stack.imgur.com/3c6hf.png

index.js

import React from 'react'
import NavBar from '../components/Navbar/Navbar';
import fetch from 'isomorphic-unfetch';

import '../styles/styles.css';

import ProductList from '../components/ProductList/ProductList';

const Index = (props) => {

    return (
        <div>
            <NavBar />
            <h1>Products</h1>
            <ProductList products={props.products} />

        </div>
    );
};

Index.getInitialProps = async () => {

    const res = await fetch('http://localhost:3000/');
    const data = await res.json()
    return {products: data}

}

export default Index;

ProductList.js

import ProductTile from '../ProductTile/ProductTile';

class ProductList extends React.Component {
    render(){
        return(
            <div className = "md:flex">

            {
                this.props.products.map(product => {
                    return (
                    <Link href={`/product?product_ID=${product.product_ID}`}>
                    <a><ProductTile product = {product} key={product.product_ID}/></a>
                    </Link>
                )})

            }

            </div>
        )
    }
}

export default ProductList;

server.js

const express = require('express');
const next = require('next');

require('dotenv').config()

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');

const pool = require('../lib/db');

//routers
const productsRouter = require('./routes/products');
const usersRouter = require('./routes/users');


app.prepare().then(() => {
  const server = express()
  server.use(cors());
  server.use(morgan('dev'));
  server.use(bodyParser.json());

  server.get('/', (req, res, next) => {
    pool.query('SELECT * FROM products', function (error, results, fields) {
      if (error) throw error;
      //console.log(results);
      res.send(results);
    });
  })

/* Routers for product router and user router here

*/

  server.use((err, req, res, next) => {
    if (!err.status) {
      err.status = 500;
    }
    res.status(err.status).send(err.message);
  });

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

回答1:


Hmm... Based on your server.js, I'd say it comes from this. In which folder is index.js? To which route it responds to ? Eventually, it could be in your routers code.

Do you see the request coming in, logged, in your server? Can you log it inside your index.js server route?



来源:https://stackoverflow.com/questions/59002970/initially-fetch-data-and-pass-props-to-another-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!