簡體   English   中英

如何在React中使用axios在一個單獨的組件中渲染一個結果?

[英]How do I only render one result in a separate component using axios in React?

編輯//

我想我的問題不是那么清楚。 當我的網址指向http:// localhost:1233 / details / '$ {parkcode}'時,我正試圖讓一個公園返回。 我在results.js文件中為url定義了param。 但是我在我的details.js中定義this.setState時遇到麻煩,只根據id來渲染park的一個結果,這也恰好是park代碼。

我是React的新手(也可能是JavaScript,我不知道了)。 我正在學習一個教程 - 而不是使用npm包作為API我決定分支出來並使用axios.get()從API獲取數據。 我能夠將組件的結果渲染到瀏覽器中,但是在添加到達路由器之后(我假設它與React路由器類似),我只能將我的API調用的一個結果渲染為我嘗試的頁面build應該只根據我定義的ID顯示一個結果。

在我的主文件(這里是Results.js)中,我能夠毫無問題地獲取數據,並使用JSX將它們包含在我的文件中並渲染它們。 我試圖在我的Details.js頁面中使用與我在該頁面中所做的邏輯相同的邏輯(該頁面應該只向路徑中的ID顯示一個結果)。

我如何在Results.js中使用axios

componentDidMount() {
    axios
      .get(
        "https://developer.nps.gov/api/v1/parks?stateCode=wa&fields=images&api_key=" +
          `${nps}`
      )

      // https://css-tricks.com/using-data-in-react-with-the-fetch-api-and-axios/
      .then(res =>
        res.data.data.map(park => ({
          description: `${park.description}`,
          fullname: `${park.fullName}`,
          states: `${park.states}`,
          parkcode: `${park.parkCode}`,
          image: `${park.images[0] ? park.images[0].url : "No Image"}`,
          designation: `${park.designation}`
        }))
      )
      .then(parks => {
        this.setState({
          parks
        });
        console.log(parks);
      });
  }

我是如何嘗試在Details.js中使用相同的邏輯

即使我進行了API調用,它也無法識別park.name。 但是,如果我硬編碼park [0] .name它可以工作。 我不知道我在這里做錯了什么。 這可能是一個明顯的問題,但幫助我。

class Details extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      loading: true,
    }
  }

  componentDidMount() {
    axios
      .get(
        "https://developer.nps.gov/api/v1/parks?stateCode=wa&fields=images&api_key=" +
          `${nps}`, 
          { id: this.props.id }

      ).then(res => {
        const park = res.data.data.map(park => ({
          description: `${park.description}`,
          fullname: `${park.fullName}`,
          states: `${park.states}`,
          parkcode: `${park.parkCode}`,
          image: `${park.images[0] ? park.images[0].url : "No Image"}`,
          designation: `${park.designation}`
        }))

        console.log(park.name);

        this.setState({
          name: park.name;
          loading: false
        })
      }).catch(err => {
        this.setState({error: err});
      })
  }

我希望頁面能夠識別GET請求中定義的id以及axios,並渲染與id相關的公園詳細信息。 但現在,它沒有做到這一點,我一直堅持這個永遠:(

我相信這是你錯了

const parks = res.data.data.map(park => ({
  description: `${park.description}`,
  fullname: `${park.fullName}`,
  states: `${park.states}`,
  parkcode: `${park.parkCode}`,
  image: `${park.images[0] ? park.images[0].url : "No Image"}`,
  designation: `${park.designation}`
}))

console.log(parks) // this should display your array of all parks

this.setState({
  parks,
  loading: false
})

displayParks(parks) {
 const allParks = parks.map((park, index) => {
   return <div key={park.parkCode}>{park.fullname}<div>
 })
}


render() {
const { parks } = this.state;

const displayParks = parks && parks.length > 0 ? this.displayParks(parks) : <div>Loading parks</div>
  return (
      <div>{ displayParks }</div>
    );
  }

當您在數組上執行.map時,您基本上創建了另一個數組,這是返回到park變量的內容。

因此,在渲染方法中,您可以遍歷parks每個項目

你可以在.then()試試這個

let park = res.data.data.map(park => ({
    description: `${park.description}`,
    fullname:    `${park.fullName}`,
    states:      `${park.states}`,
    parkcode:    `${park.parkCode}`,
    image:       `${park.images[0] ? park.images[0].url : "No Image"}`,
    designation: `${park.designation}`
}))
park = park[0]; // convert arrays of parks to single park
console.log(park.fullname); // now you can use `park.fullname`

或這個

const park = {
    description: `${res.data.data[0].description}`,
    fullname:    `${res.data.data[0].fullName}`,
    states:      `${res.data.data[0].states}`,
    parkcode:    `${res.data.data[0].parkCode}`,
    image:       `${res.data.data[0].images[0] ? park.images[0].url : "No Image"}`,
    designation: `${res.data.data[0].designation}`
}
console.log(park.fullname); // now you can use `park.fullname`

否則在API中執行

我認為您可以先為您的回復設置狀態,然后嘗試顯示它們

同樣的:

state = {
  result: []
}

componentDidMount() {
  axios
    .get("https://developer.nps.gov/api/v1/parks?stateCode=wa&fields=images&api_key=" +`${nps}`).then((res) => {
      this.setState({result: res.data.data})
  })
}

render(){
  const result = this.state.result.map((el, index) => {
    return(
      //data
    )
  })
  return(
     <div>
       {result}
     </div>
  )
}

您的代碼中有一些不必要的部分。 您不需要像在setState部分中那樣構建數據。 您正在獲取停車清單,它已經是結構化數據。 因此,只需使用您獲得的數據設置您的狀態即可。

之后,您可以映射此數據並使用React Router的鏈接渲染公園。 您可以使用parkCode作為Link的URL參數。 在“ Details組件中,您可以提取此parkCode並對停車詳細信息發出新請求,然后將其設置為您的狀態。

我提供了一個例子。

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Results from "./Results";
import Details from "./Details";

const Routes = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Results} />
      <Route path="/details/:parkCode" component={Details} />
    </Switch>
  </Router>
);

ReactDOM.render(<Routes />, document.getElementById("root"));

結果

import React from "react";
import axios from "axios";
import { Link } from "react-router-dom";

class Results extends React.Component {
  state = {
    parks: [],
    loading: true,
  };

  componentDidMount() {
    axios(
      "https://developer.nps.gov/api/v1/parks?stateCode=wa&fields=images&api_key=LbqZVj21QMimfJyAHbPAWabFaBmfaTZtseq5Yc6t"
    ).then(res => this.setState({ parks: res.data.data, loading: false }));
  }

  renderParks = () =>
    this.state.parks.map(park => (
      <Link to={`/details/${park.parkCode}`} key={park.parkCode}>
        <div>{park.fullName}</div>
      </Link>
    ));

  render() {
    return (
      <div>{this.state.loading ? <p>Loading...</p> : this.renderParks()}</div>
    );
  }
}

export default Results;

細節

import React from "react";
import axios from "axios";

class Details extends React.Component {
  state = { park: "", loading: true };

  componentDidMount() {
    const { match } = this.props;
    axios(
      `https://developer.nps.gov/api/v1/parks?parkCode=${match.params.parkCode}&api_key=${nps}`
    ).then(res => this.setState({ park: res.data.data[0], loading: false }));
  }

  render() {
    return (
      <div>
        {this.state.loading ? <p>Loading...</p> : this.state.park.description}
      </div>
    );
  }
}

export default Details;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM