![](/img/trans.png)
[英]Trying to fetch data from a GraphQL API and then pass it as props to a component
[英]How to fetch data from api and pass it as props
我正處於反應的學習階段並試圖弄清楚如何獲取api數據並將其作為道具傳遞,所以我在github中創建了自己的api文件並嘗試從中獲取api數據,這里是以下鏈接:
https://raw.githubusercontent.com/faizalsharn/jokes_api/master/jokesData.js
由於某種原因,數據不是從api獲取而不是作為道具傳遞給某人,請解釋我在哪里做錯了,請原諒我,如果這里有任何明顯的錯誤我仍然在初學者水平
App.js
import React, {Component} from "react"
import Joke from "./joke"
class App extends Component {
constructor() {
super()
this.state = {
loading: false,
jokeComponents: []
}
}
componentDidMount() {
this.setState({loading: true})
fetch("https://raw.githubusercontent.com/faizalsharn/jokes_api/master/jokesData.js")
.then(response => response.json())
.then(data => {
this.setState({
loading: false,
jokeComponents: data.jokesData.map(joke => <Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />)
})
})
}
render() {
const text = this.state.loading ? "loading..." : this.state.jokeComponents
return (
<div>
{text}
</div>
)
}
}
export default App
joke.js
import React from "react"
function Joke(props) {
return (
<div>
<h3 style={{display: !props.question && "none"}}>Question: {props.question}</h3>
<h3 style={{color: !props.question && "#888888"}}>Answer: {props.punchLine}</h3>
<hr/>
</div>
)
}
export default Joke
我檢查了API,發現在fetch API中調用response.json()
時它無法正常工作。
這是由於API響應中的錯誤。 您只需要返回一個裸數組,而不是返回帶有變量的API。
作為參考,請檢查Jsonplaceholder Fake API的返回json。 https://jsonplaceholder.typicode.com/posts
希望這可以解決您的錯誤。
另外,對於jokeComponents的狀態,請在響應中傳遞數組,而不是操縱數據。 如果狀態發生了變化,只需在render()
函數中使用.map
作為jokeArray。 :)
要在加載內容后顯示內容並隱藏加載指示符,請使用模擬異步操作的函數,然后顯示數據。 我已經使用其他API展示了此示例,因為您的API存在問題。 我希望你解決這個問題。 還設置標頭以允許跨域數據訪問。
App.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Joke from "./Joke";
class App extends Component {
constructor() {
super();
this.state = {
loading: true,
jokeComponents: []
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts",{
headers: { crossDomain: true, "Content-Type": "application/json" }
}).then(response=>response.json())
.then(data => {
console.log(data);
this.setState({
jokeComponents: data.map(joke => (
<Joke
key={joke.id}
question={joke.title}
punchLine={joke.body}
/>
))
});
});
demoAsyncCall().then(() => this.setState({ loading: false }));
}
render() {
const { loading } = this.state;
if(loading) {
return "loading...";
}
return <div>{this.state.jokeComponents}</div>;
}
}
function demoAsyncCall() {
return new Promise((resolve) => setTimeout(() => resolve(), 2500));
}
ReactDOM.render(<App />, document.getElementById('root'));
下面的CodeSandbox中設置了相同的工作代碼:
Gideon Arces正確地解釋了你的第一個錯誤,但還有更多工作要做:
您需要將.json文件格式化為json,這與javascript不同。 例如,雖然這是javascript {id: 1, question: "?"}
但它不是json。 Json必須格式如下: {"id": "1", "question":"?"}
帶有引號的屬性名稱。
您需要在componentDidMount中進行數據提取並在那里調用setState
您需要從狀態中提取數據並在render()
中render()
組件。 通常,這是通過創建組件數組然后將它們放入{}
內的返回來完成的。 在此處查看更多信息: 列表和密鑰
在嘗試將ui與api結合使用之前,首先將虛擬數據硬編碼到組件中始終是一個好主意。 請參閱下面的componentDidMount()
,其中我硬編碼了一些笑話。 這樣,您就可以將ui代碼中的錯誤與網絡/ api代碼中的錯誤隔離開來。
class App extends React.Component {
constructor() {
super();
this.state = {
loading: false,
jokes: []
};
}
componentDidMount() {
// this.setState({loading: true})
// fetch("https://raw.githubusercontent.com/faizalsharn/jokes_api/master/jokesData.js")
// .then(response => response.json())
// .then(data => {
// console.log(data);
// this.setState({
// loading: false,
// jokes: data
// })
// })
const json = `[
{
"id": "1",
"question": "?",
"punchLine": "It’s hard to explain puns to kleptomaniacs because they always take things literally."
},
{
"id": "2",
"question": "What's the best thing about Switzerland?",
"punchLine": "I don't know, but the flag is a big plus!"
}
]`;
const jokes = JSON.parse(json);
this.setState({ jokes });
}
render() {
const jokeComponents = this.state.jokes.map(joke => (
<Joke key={joke.id} question={joke.question} punchLine={joke.punchLine} />
));
console.log(jokeComponents);
const text = this.state.loading ? "loading..." : jokeComponents;
return <div>Text: {text}</div>;
}
}
function Joke(props) {
console.log("joke props:", props);
return (
<div>
<h3 style={{ display: !props.question && "none" }}>
Question: {props.question}
</h3>
<h3 style={{ color: !props.question && "#888888" }}>
Answer: {props.punchLine}
</h3>
<hr />
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.