简体   繁体   中英

Passing data from a single JSON file from parent to child component in React using dynamic routes

I'm trying to create a project that makes use of React dynamic routes. Basically, my project does this: when I click on the Shop Page, a local JSON files is rendered in the Shop component, then when I click on an item from the Shop Component, a dynamic route is being created and its respective data is being show.

Eg : instead of showing the 'Description Placeholder' text, I want to display the cars description. In the case of Ford KA, I want it to display 'Mini', for the Ford Fiesta I want 'Hatchback' and so on.

How can I pass this data from a parent to a child component? I looked up on Google and some tutorials make use of two API: they are comparing the id of one API which holds a list of items to the id of the other API which holds the item details. The problem is that I don't think I can do this with a local JSON file. I tried passing some data as props from the Shop component to ShopItems, but my code caused a plethora of errors in the console, so I ended up erasing that code to make this functional again.

Here is my Code and a CodeSandbox link :

App.js

import React from 'react';
import './App.sass';
import Nav from './components/Nav';
import About from './components/About';
import Shop from './components/Shop';
import ShopItem from './components/ShopItem';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route path='/' exact component={Home}/>
          <Route path='/about' component={About} />
          <Route path='/shop' exact component={Shop} />
          <Route path='/shop/:id' component={ShopItem} />
        </Switch>
      </div>
    </Router>
  );
}

const Home = () => {
  return (
  <div>
    <h1>Home Page</h1>
  </div>
)};

export default App;

Nav.js

import React from 'react';
import '../App.sass';
import { Link } from 'react-router-dom';
function Nav() {

  const navStyle = {
    color: 'white'
  };
  return (
    <div>
      <nav>
        <Link to='/'>
          <h3> Logo </h3>
        </Link>
        <ul className='nav-links'>
          <Link style={navStyle} to='/about'>
            <li>About</li>
          </Link>
          <Link style={navStyle} to='/shop'>
            <li>Shop</li>
          </Link>
        </ul>
      </nav>
    </div>
  );
}

export default Nav;

Nav.sass

nav
  display: flex
  justify-content: space-around
  align-items: center
  min-height: 10vh
  background: gray
  .nav-links
    width: 50%
    display: flex
    justify-content: space-around
    align-items: center
    list-style: none

Shop.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class Shop extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }

  componentDidMount() {

  fetch('./data.json')
  .then((res) => res.json())
  .catch(err => console.log(err))
  .then((data) => {
    //console.log('data:', data);
    this.setState({
      data: data
    })
  })
}

  render() {
    const { data } = this.state
    return (
      <div>
        {data.map(data =>
          <h1>
            <Link to={`/shop/${data.id}`}>{data.name}</Link>
          </h1>)}
      </div>
    )
  }
}

export default Shop;

ShopItem.js

import React, { Component } from 'react';
class ShopItem extends Component {

  render() {
    return(
      <div>Description Placeholder</div>
    )
  }
}

export default ShopItem;

data.json

[{"id": 1,"name": "Ford Ka", "description": "Mini"},
{"id": 2, "name": "Ford Fiesta", "description": "Hatchback"},
{"id": 3, "name": "Ford Focus", "description": "Hatchback"},
{"id": 4, "name": "Ford Mondeo", "description": "Sedan"}
]

You Do like

class ShopItem extends Component {

  constructor(props) {
    super(props);
    this.state = {
      detail: {}
    };
  }

  componentDidMount() {

// getting the params id value here

 let id = this.props.match.params.redirectParam;
  fetch('./data.json')
  .then((res) => res.json())
  .catch(err => console.log(err))
  .then((data) => {

   ****// Updated filter to find the Id here****

    this.setState({
      detail: data.find(data => data.id === id);
    })
  })
}
 render() {
    return(
      <div>{this.state.detail.description}</div>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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