ReactJs - 如何在一个Component内传递数据

时间:2017-05-05 02:07:27

标签: javascript reactjs

我想将数据从axiosDidMount function传递到

 <p className='title' id='boldTitle'>{data goes here}</p>

我可以使用console.log数据并且它正常工作,在我的例子中它是一个字符串&#34;纽约市&#34;。

当我在Search.js组件中编写一些输入时,我得到了这一点,并通过this.props.userQuery传递给Results.js组件。因此response.data[1][1]正在更新并且在我写入输入时生活在console.log中,但是我将从维基百科到达最终目的地的数据传递出去了。

在此示例中传递此数据的正确方法是什么?

import React from 'react';
import axios from 'axios';

export default class Results extends React.Component {

  axiosDidMount(userQuery) {
    //const fruits = [];
    const wikiApiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&origin=*&search=';
    const wikiApiUrlWithQuery = wikiApiUrl + userQuery;
    axios.get(wikiApiUrlWithQuery) 
      .then(response => {
        console.log(response.data[1][1]); //New York City
        console.log(typeof(response.data[1][1])); //string
        //console.log(response.data[2])
        //console.log(response.data[3])
        //fruits.push(response.data[1]);
      }) 
      .catch(err => {
        console.log('Error: =>' + err); 
      });
    //return fruits;
  }

  render() {

    //this.props.userQuery from Search.js
    const test = this.axiosDidMount(this.props.userQuery);

    return(
      <div>
          <a className='title' href="" target='_blank'>
            <div className='result'>
              <p className='boldTitle'>{data goes here}</p>
            <p></p>
            </div>
          </a>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您应该将您的疑虑分开。制作数据接收组件或处理数据检索的容器组件,并在组件可用时有条件地呈现需要数据的组件。以下内容:

import React, { Component } from 'react';
import axios from 'axios';

const PresentationComponent = (props) => {
  // return mark with data
}

const PlaceHolderComponent = (props) => {
  // return placeholder markup
}

export default class DataReceivingWrapper extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      data: null
    }
  }
  
  componentDidMount() {
    axios.get(...)
      .then(data) {
        this.setState(Object.assign({}, this.state, { data: data }))
      }...
  }
  
  render() {
      if (this.props.data) {
        return <PresentationComponent />;
      } else {
        return <PlaceHolderComponent />; // or null
      }
  }
}

相关问题