我对 ReactJS 还很陌生,所以这是我在其中使用 Fetch 的实现。
class App extends React.Component {
function postData(url, data) {
// Default options are marked with *
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}
render() {
const test_content = ["first", "second", "third"];
const initial_data = {
'id': 1,
'model-name': 'Joke'
};
postData('/start-jokes/', initial_data)
.then(data => console.log(data)
) // JSON from `response.json()` call
.catch(error => console.error(error));
const jokes_div = test_content.map((item, i) => (
<div key={i} className="card col-md-7">
<div className="card-body">
{item}
</div>
</div>
));
return <div className="container" id="jokes">{jokes_div}</div>;
}
}
// ========================================
ReactDOM.render(
<App />,
document.getElementById('root')
);
这工作正常,控制台会记录此响应。
Object { status: "ok", jokes: Array[10], ref-id: 11 }
笑话数组在对象中具有 id 和文本,文本将与 test_content
相同使用,以使用此处所示的自己的唯一键 id
填充项目
任何有关如何现在从那里填充的指示将不胜感激。
最佳答案
切勿在渲染中调用 api。如果您希望在页面渲染时加载数据,请调用 componentDidMount 中的函数;否则,如果您想加载某些其他事件或某些输入更改,请在 onChange 事件中调用它,并且如上所述不需要返回结果,您可以 setState 响应。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data : [],
}
}
componentDidMount(){
this.postdata()
}
postdata(){
var self = this;
fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(response => response.json()).then((json) => {
self.setState({ data : json.data }) // which ever the key hold the data
})
}
render(){
return(
<div>
{this.state.data.length == 0 &&
<div> No options available.</div>
}
{this.state.data.length > 0 &&
<div className="container" id="jokes">
{this.state.data.map(function(item,i){
return(
<div key={i} className="card col-md-7">
<div className="card-body">
{item} // here you are getting object in item. Get the key from the object like item.name
</div>
</div>
)
})}
</div>
}
</div>
)
}
}
关于javascript - 将 Fetch 与 ReactJS 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50887286/