简体   繁体   English

使用动态路由将数据从单个 JSON 文件从父组件传递到 React 中的子组件

[英]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.我正在尝试创建一个使用 React 动态路由的项目。 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.基本上,我的项目是这样做的:当我单击 Shop Page 时,Shop 组件中会呈现一个本地 JSON 文件,然后当我单击 Shop 组件中的一个项目时,正在创建一个动态路由,并且正在创建其各自的数据展示。

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.对于福特 KA,我希望它显示“Mini”,对于福特嘉年华,我希望它显示“Hatchback”等等。

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.我在谷歌上查了一下,一些教程使用了两个 API:他们正在比较一个包含项目列表的 API 的 ID 和另一个包含项目详细信息的 API 的 ID。 The problem is that I don't think I can do this with a local JSON file.问题是我认为我不能用本地 JSON 文件做到这一点。 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.我尝试将一些数据作为道具从 Shop 组件传递到 ShopItems,但是我的代码在控制台中导致了大量错误,因此我最终删除了该代码以使其再次起作用。

Here is my Code and a CodeSandbox link :这是我的代码和 CodeSandbox链接

App.js应用程序.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导航.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商店.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 ShopItem.js

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

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

export default ShopItem;

data.json数据.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 // 在此处获取 params id 值

 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>
    )
  }
}

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

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