简体   繁体   English

最初获取数据并将 props 传递给另一个组件

[英]Initially fetch data and pass props to another component

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.我已经从头到尾阅读了 Next.js 文档,并在网上搜索了几个小时。 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.当 Index.js 被加载时,它会向我的数据库(通过)express 发送一个请求,并返回一个 json 响应。 The intention is for my ProductList component to .map() this response - which has been passed to it via props - into my individual products.目的是让我的 ProductList 组件将此响应(已通过道具传递给它) .map() 到我的单个产品中。

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.使用下面的代码,当我最初加载另一个页面然后链接到它的客户端时,我可以让我的 index.js 呈现产品。 However, I can't get Index.js to load my products if I initially load this page.但是,如果我最初加载此页面,则无法让 Index.js 加载我的产品。

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

index.js索引.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产品列表.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服务器.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}`)
  })
})

Hmm... Based on your server.js , I'd say it comes from this.嗯...根据您的server.js ,我会说它来自于此。 In which folder is index.js ? 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?你能把它记录在你的index.js服务器路由中吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM