0

Lo que estoy tratando de hacer es que esta parte

const topics = [
  {
    name: 'React Router',
    id: 'react-router',
    description: 'Declarative, component based routing for React',
    resources: [
      {
        name: 'URL Parameters',
        id: 'url-parameters',
        description: "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        url: 'https://tylermcginnis.com/react-router-url-parameters'
      },
      {
        name: 'Programatically navigate',
        id: 'programmatically-navigate',
        description: "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        url: 'https://tylermcginnis.com/react-router-programmatically-navigate/'
      }
    ]
  },
  {
    name: 'React.js',
    id: 'reactjs',
    description: 'A JavaScript library for building user interfaces',
    resources: [
      {
        name: 'React Lifecycle Events',
        id: 'react-lifecycle',
        description: "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        url: 'https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/'
      },
      {
        name: 'React AHA Moments',
        id: 'react-aha',
        description: "A collection of 'Aha' moments while learning React.",
        url: 'https://tylermcginnis.com/react-aha-moments/'
      }
    ]
  },
  {
    name: 'Functional Programming',
    id: 'functional-programming',
    description: 'In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.',
    resources: [
      {
        name: 'Imperative vs Declarative programming',
        id: 'imperative-declarative',
        description: 'A guide to understanding the difference between Imperative and Declarative programming.',
        url: 'https://tylermcginnis.com/imperative-vs-declarative-programming/'
      },
      {
        name: 'Building User Interfaces with Pure Functions and Function Composition',
        id: 'fn-composition',
        description: 'A guide to building UI with pure functions and function composition in React',
        url: 'https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/'
      }
    ]
  }
]

lo convierta en un JSON en otro proyecto de prueba lo hice de esta manera

class App extends Component {
  state = {
    topics: []
  }
 
  async componentDidMount(){
    const topics = await (await fetch('http://localhost:4000/data')).json()
    console.log(topics)
    this.setState({ topics })
  }
  render() {
    const { topics } = this.state
    return (

pero en el nuevo proyecto de prueba lo tengo desarrollado todo por funciones separadas

import React, { Component } from 'react'
import {
  BrowserRouter as 
  Router,
  Route,
  Link,
} from 'react-router-dom'

const topics = [
  {
    name: 'React Router',
    id: 'react-router',
    description: 'Declarative, component based routing for React',
    resources: [
      {
        name: 'URL Parameters',
        id: 'url-parameters',
        description: "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        url: 'https://tylermcginnis.com/react-router-url-parameters'
      },
      {
        name: 'Programatically navigate',
        id: 'programmatically-navigate',
        description: "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        url: 'https://tylermcginnis.com/react-router-programmatically-navigate/'
      }
    ]
  },
  {
    name: 'React.js',
    id: 'reactjs',
    description: 'A JavaScript library for building user interfaces',
    resources: [
      {
        name: 'React Lifecycle Events',
        id: 'react-lifecycle',
        description: "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        url: 'https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/'
      },
      {
        name: 'React AHA Moments',
        id: 'react-aha',
        description: "A collection of 'Aha' moments while learning React.",
        url: 'https://tylermcginnis.com/react-aha-moments/'
      }
    ]
  },
  {
    name: 'Functional Programming',
    id: 'functional-programming',
    description: 'In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.',
    resources: [
      {
        name: 'Imperative vs Declarative programming',
        id: 'imperative-declarative',
        description: 'A guide to understanding the difference between Imperative and Declarative programming.',
        url: 'https://tylermcginnis.com/imperative-vs-declarative-programming/'
      },
      {
        name: 'Building User Interfaces with Pure Functions and Function Composition',
        id: 'fn-composition',
        description: 'A guide to building UI with pure functions and function composition in React',
        url: 'https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/'
      }
    ]
  }
]

function Resource ({ match }) {
  const topic = topics.find(({ id }) => id === match.params.topicId)
    .resources.find(({ id }) => id === match.params.subId)

  return (
    <div>
      <h3>{topic.name}</h3>
      <p>{topic.description}</p>
      <a href={topic.url}>More info.</a>
    </div>
  )
}

function Topic ({ match }) {
  const topic = topics.find(({ id }) => id === match.params.topicId)

  return (
    <div>
      <h2>{topic.name}</h2>
      <p>{topic.description}</p>

      <ul>
        {topic.resources.map((sub) => (
          <li key={sub.id}>
            <Link to={`${match.url}/${sub.id}`}>{sub.name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={`${match.path}/:subId`} component={Resource} />
    </div>
  )
}

function Topics ({ match }) {
  return (
    <div>
      <h1>Topics</h1>
      <ul>
        {topics.map(({ name, id }) => (
          <li key={id}>
            <Link to={`${match.url}/${id}`}>{name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={`${match.path}/:topicId`} component={Topic}/>
    </div>
  )
}

function Home () {
  return (
    <h1>
      Home.
    </h1>
  )
}

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <ul>
            <li><Link to='/'>Home</Link></li>
            <li><Link to='/topics'>Topics</Link></li>
          </ul>

          <hr />

          <Route exact path='/' component={Home} />
          <Route path='/topics' component={Topics} />
        </div>
      </Router>
    )
  }
}

export default App

Mi pregunta es como puedo hacer para que tenga el JSON por medio de un link sin tener que escribirlo directamente en el codigo

Adjunto todo el codigo funcional gracias por la ayuda.

1
  • No se entiende muy bien qué deseas hacer. Además que no creo que la pregunta tenga alguna relación con el título del post. Esto puede ocasionar que no muchas personas se interesen en responderte Commented el 31 ago. 2018 a las 17:05

2 respuestas 2

1

Podrías importar el archivo json:

import myJsonDatae from './jsonData.json';

Donde myJsonData.json está ubicado en la misma ruta y tiene ésta pinta:

[
  {
    "name": "React Router",
    "id": "react-router",
    "description": "Declarative, component based routing for React",
    "resources": [
      {
        "name": "URL Parameters",
        "id": "url-parameters",
        "description": "URL parameters are parameters whose values are set dynamically in a page's URL. This allows a route to render the same component while passing that component the dynamic portion of the URL so it can change based off of it.",
        "url": "https://tylermcginnis.com/react-router-url-parameters"
      },
      {
        "name": "Programatically navigate",
        "id": "programmatically-navigate",
        "description": "When building an app with React Router, eventually you'll run into the question of navigating programmatically. The goal of this post is to break down the correct approaches to programmatically navigating with React Router.",
        "url": "https://tylermcginnis.com/react-router-programmatically-navigate/"
      }
    ]
  },
  {
    "name": "React.js",
    "id": "reactjs",
    "description": "A JavaScript library for building user interfaces",
    "resources": [
      {
        "name": "React Lifecycle Events",
        "id": "react-lifecycle",
        "description": "React Lifecycle events allow you to tie into specific phases of a components lifecycle",
        "url": "https://tylermcginnis.com/an-introduction-to-life-cycle-events-in-react-js/"
      },
      {
        "name": "React AHA Moments",
        "id": "react-aha",
        "description": "A collection of 'Aha' moments while learning React.",
        "url": "https://tylermcginnis.com/react-aha-moments/"
      }
    ]
  },
  {
    "name": "Functional Programming",
    "id": "functional-programming",
    "description": "In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.",
    "resources": [
      {
        "name": "Imperative vs Declarative programming",
        "id": "imperative-declarative",
        "description": "A guide to understanding the difference between Imperative and Declarative programming.",
        "url": "https://tylermcginnis.com/imperative-vs-declarative-programming/"
      },
      {
        "name": "Building User Interfaces with Pure Functions and Function Composition",
        "id": "fn-composition",
        "description": "A guide to building UI with pure functions and function composition in React",
        "url": "https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/"
      }
    ]
  }
]

De manera que al cargar el componente puedes setear en el state a la llamada al método ComponentDidMount.

componentDidMount() {
  this.setState({ data: myJsonData });
}
0

lo que puede hacer, para mantener el codigo mas ordenado es, crear un mock api con su data, puede hacerlo aca: https://www.mockapi.io/login.

Luego, puede usar axios, fetch, o super-agent para hacer el get (traer la informacion) asi:

componentDidMount() {
axios.get(`https://'link generado aca'`)
  .then(res => {
    const informacion = res.data;
    this.setState({ informacion });
  })

}

Y con eso deberia poder hacerlo.

Tambien, para mantener el codigo mas estrucurado, podria hacer una funcion que se encargue de llamar el data. asi componentDidMount, se encargaria unicamente de settear el nuevo estado.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.