【发布时间】:2019-09-29 22:01:52
【问题描述】:
我在App.js 中有一个状态,其中填充了 API 返回的动物数据。可以在加载的组件上使用this.state.animals 访问此数据,但我的问题是在将路由更改为/animals 时,我无法再调用this.state.animals。就好像我不再有权访问或数据消失了。当我导航到任何组件时,如何将状态传递给它们?
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
【问题讨论】:
-
您是否尝试在 Animals 中以
this.props.parentState的身份访问它? -
如果你想在从一条路线导航到另一条路线时持久化数据,我认为你需要使用 Redux 或 Flux。
-
@NicholasTower 你可能正在做一些事情......会报告回来
-
@NicholasTower 确实是这样。感谢您指出这一点,效果很好!
标签: javascript reactjs react-router state