简体   繁体   中英

Pass state from App.js to React Router component

I have a state in App.js that gets populated with animal data returned by an API. This data is accessible with this.state.animals on the component that is loaded, but my problem is when changing routes to /animals , I can no longer call this.state.animals . It's as if I no longer have access or the data is gone. How can I pass the state to any component when I navigate to them?

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'
import Animals from './components/Animals'

class App extends Component {
  state = {
    animals: []
  }

  componentDidMount() {
    fetch('animals api path here')
    .then(result => result.json())
    .then((data) => {
      this.setState({ animals: data })
    })
    .catch(console.log)
  }

  render() {
    return (
          <Router>
            <NavLink to="/animals">animals</NavLink>
            <Route exact path="/animals" render={()=> <Animals parentState={this.state.animals} />} />
          </Router>
    );
  }
}

export default App

components/Animals.js

import React, { Component } from 'react'

class Animals extends Component {
  render() {
    console.log(this.state.animals)
    return (
      <h2>Animals</h2>
    //<div>I would loop through and list the animals if I could...</div>
    )
  }
}

export default Animals

在此示例中,如果您要访问动物数据,则它将在动物组件内部为{this.props.parentState}

Your Route declaration is defined outside the context of the router. When using React-Router, all your components should have among their ancestors a . Usually, is the top-level component rendered in (at least if you are not using other libraries that need root-context definition, like Redux).

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