问题
So I've got both chunks of code written for both the API request, as well as the grid rendering, however I'm confused as to how to combine the two in a react environment. Any suggestions?
(this is using react-axios)
<Request
method="get", /* get, delete, head, post, put and patch - required */
url="http://coincap.io/front", /* url endpoint to be requested - required */
debounce={50} /* minimum time between requests events - optional */
onSuccess={(response)=>{}} /* called on success of axios request - optional */
onError=(error)=>{} /* called on error of axios request - optional */
/>
I'm looking to remove this hardcoded data, and render the grid with the data pulled from the api call to CoinCap.io
// Grid data as an array of arrays
const list = [
['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */ ]
// And so on...
];
function cellRenderer ({ columnIndex, key, rowIndex, style }) {
return (
<div
key={key}
style={style}
>
{list[rowIndex][columnIndex]}
</div>
)
}
ReactDOM.render(
<Grid
cellRenderer={cellRenderer}
columnCount={list[0].length}
columnWidth={150}
height={300}
rowCount={list.length}
rowHeight={60}
width={700}
/>,
document.getElementById('root')
);
回答1:
You can insert the results of your API call into the component's state. Inside your Request component, try this:
onSuccess={(response)=> this.setState({ list: response });
. You might also consider making the API call inside a component lifecycle method like componentWillMount
instead of the Axios component.
Then in your render method, replace your reference to the local placeholder list
with this.state.list
. Obviously you'll need to tweak this to make it work within your component structure, but without seeing the complete component this should at least get you moving in the right direction.
来源:https://stackoverflow.com/questions/44663944/trying-to-combine-an-api-request-with-a-grid-rendering