【问题标题】:Pass state from App.js to React Router component将状态从 App.js 传递给 React Router 组件
【发布时间】: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


【解决方案1】:

在这个例子中,如果你想访问动物数据,它会在动物组件里面{this.props.parentState}

【讨论】:

    【解决方案2】:

    您的Route 声明是在路由器上下文之外定义的。当使用 React-Router 时,你所有的组件都应该在它们的祖先中有一个 .通常,是渲染的顶级组件(至少如果您不使用其他需要根上下文定义的库,例如 Redux)。

    【讨论】:

    • 这是粘贴我的代码的问题,更新了我上面的代码。
    • 然后,正如 Nicholas Tower 所指出的,只需在您的动物组件中以 this.props.parentState 的形式访问它
    猜你喜欢
    • 2020-05-18
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 2019-01-20
    • 2022-01-18
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多