- React Material:UI Cookbook
- Adam Boduch
- 210字
- 2021-06-24 15:49:40
How it works...
Let's start with the fetchPanelContent() API function:
const fetchPanelContent = index =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
[
'First panel content...',
'Second panel content...',
'Third panel content...',
'Fourth panel content...'
][index]
),
1000
)
);
Since this is just a mock, it returns a promise directly. It uses setTimeout() to simulate latency, similar to what you would experience using a real API. The promise resolves with the string value that's looked up from an array, based on the index argument.
Next, let's look at the onChange handler function that's called when ExpansionPanel expands:
const onChange = index => (e) => {
if (!panels[index].content) {
fetchPanelContent(index).then(content => {
const newPanels = [...panels];
newPanels[index] = { ...newPanels[index], content };
setPanels(newPanels);
});
}
};
First, this function checks if the panel that's expanded has any content in its state. If not, you know that you have to fetch it by calling fetchPanelContent(). When the returned promise resolves, you can call setPanels() to update the panels array and set the content at the appropriate index.
The rest of your component just renders the ExpansionPanel components based on the panels array, using the content state as the panel content. When content is updated, it is reflected in the rendered content.