问题
I'm completely new to React and having a hard time understanding it.
I've been tasked with creating a really simple API fetch to an OData endpoint.
Now, I've come across this library https://www.npmjs.com/package/react-odata
Which looks fantastic! However I just do not understand how to even get something like this working.
I understand the very basic principles of how react works and have gone through many basic tutorials. But for whatever reason I can not get my head around this one.
So how could I use this library to simply query an OData endpoint and display the raw data?
回答1:
So the issue with this, is that I didn't understand that I still have to explicitly make the call and return the data from that.
import React, { Component } from 'react';
import Fetch from 'react-fetch-component';
import OData from 'react-odata';
const baseUrl = 'http://services.odata.org/V4/TripPinService/People';
const query = { filter: { FirstName: 'Russell' } };
export default class App extends Component {
render() {
return (
<div>
<h1>Basic</h1>
<OData baseUrl={baseUrl} query={query}>
{({ loading, data, error }) => (
<div>
{loading && <span>Loading... (()=>{console.log(loading)}) </span>}
{data && data.value.map((d, i) => <div key={i} id={i}>{d.FirstName}</div>)}
</div>
)}
</OData>
</div>
);
}
/* Setup consistent fetch responses */
componentWillMount() {
fetch('http://services.odata.org/V4/TripPinService/People')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.value[0].FirstName
})
.catch((error) => {console.error(error)});
}
}
from the given link in the question I found that this component used the react-fetch-component as a base to make the call.
回答2:
It seems that the package you linked would expose a React component that you would use to wrap your own components so you would have access to the fetched data and could pass it down as properties. At least that is what I understand from its README.
I imagine it would be something like this:
<OData baseUrl={baseUrl} query={query}>
{ ({ loading, error, data }) => (
<div>
<YourComponent data={data} />
</div>
)}
</OData>
This would be using react-odata, but you don't need that package to do what you want. You could just do a regular AJAX call on the URL and feed your components with the returned data.
This post may help: http://andrewhfarmer.com/react-ajax-best-practices/
来源:https://stackoverflow.com/questions/45043913/simple-react-and-odata