[英]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. 我在
App.js
中有一个状态,该状态填充有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
. 可以使用已加载的组件上的
this.state.animals
访问此数据,但是我的问题是,更改/animals
路由时,无法再调用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 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 组件/ 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. 您的
Route
声明是在路由器上下文之外定义的。 When using React-Router, all your components should have among their ancestors a . 使用React-Router时,所有组件的祖先中都应有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).
通常,是渲染的顶级组件(至少在不使用其他需要根上下文定义的库(例如Redux)的情况下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.