代码之家  ›  专栏  ›  技术社区  ›  O P

将状态从app.js传递到react router组件

  •  0
  • O P  · 技术社区  · 6 年前

    我有一个州在 App.js 用API返回的动物数据填充。此数据可通过访问 this.state.animals 在加载的组件上,但我的问题是将路由更改为 /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
    

    组件/动物.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
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Brad Ball    6 年前

    在这个例子中,如果您想访问动物数据,它将是 {this.props.parentState} 动物成分内部

        2
  •  0
  •   Keilath    6 年前

    你的 Route 声明是在路由器上下文之外定义的。当使用React路由器时,所有组件都应该具有它们的祖先A。通常,是呈现在中的顶级组件(至少如果不使用其他需要根上下文定义的库,如redux)。

    推荐文章