【问题标题】:need assistance on react router在反应路由器上需要帮助
【发布时间】:2019-06-21 00:58:44
【问题描述】:

我是新手,我无法将数组作为道具传递

在这个函数中,我从 flickr api 请求数据以显示照片,我使用 setState 来 cats 来保存该数据数组

//this function will retrieve the CATS pictures

   renderCats = () => {
    //fetch data from flickr
    axios 
      .get(
        ` https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${apiKey}&tags=cats&per_page=24&format=json&nojsoncallback=1`
      )
      .then(response => { //set the response so that pics will be equal to the data array containing cat photos from flickr
        console.log(response)
        this.setState({
          cats: response.data.photos.photo, 
          loading: false //initialize a loading state to display a loading message
        });
      })
      .catch(error => { //this catch method outputs a message to the console, should axios fail to retrieve data
        console.log("Something went wrong, could not access data", error);
      });
  }; 

然后在 render() 中我尝试使用下面的代码 sn-p,其中 /cats 是我的导航链接,我尝试渲染一个名为 Cats 的组件,但同时我试图通过使用 data={this.state.cats} 的数据数组

 <Route path="/cats" render={ <Cats data={this.state.cats} /> } /> 

这也是我在我的 App 组件顶部所拥有的,我在其中使用 super() this.state 表示猫:[],我认为我挣扎的原因是因为我在这两者之间搞混了。 state 和 this.setState,任何改进我的代码的有用提示将不胜感激

class App extends Component { //Class components need to extend  React.Component, and class components require the render()
   constructor() {
     //state for data we want to display from flickr
     super();
     this.state = {
       pics: [], //this array will hold the pictures that will render as soon as the page loads
       cats: [],
       loading: true
     };
   }

   componentDidMount() {
     this.performSearch(); //call performSearch function on the componentDidMount() life cycle
     this.renderCats()
   }

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您的代码看起来不错,除了 Route needs to be a function 上的 render 属性。

     <Route path="/cats" render={ () => <Cats data={this.state.cats} /> } /> 
    

    如果你不需要它是一个函数,你可以使用component来代替:

     <Route path="/cats" component={ <Cats data={this.state.cats} /> } /> 
    

    【讨论】:

      【解决方案2】:

      错误在于您传递道具的方式。在你的例子中,

      &lt;Route path="/cats" render={ &lt;Cats data={this.state.cats} /&gt; } /&gt;

      data 属性基本上会被忽略。但是,如果你这样传递:

      <Route
        path="/cats"
        render={(props) => <Cats {...props} data={this.state.cats} />}
      />
      

      您将可以访问它。但是,为了让事情更简单,我是否建议将实际的数据获取函数移到需要它的组件中?这样,如果您要获取 20 种不同的东西,比如猫、狗、老鼠,具体取决于您的设置,您将渲染块整个应用程序以获取您可能需要或不需要的数据。

      【讨论】:

        猜你喜欢
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-13
        相关资源
        最近更新 更多