问题
I'm new to Javascript/React so I'm not sure how to implement this into my recursive function. I have a nested menu of json objects set up, and want to add little arrows indicating if there is another level to click to or not. Since my menu is made up of heavily nested json objects, I used recursion to go through all the objects and render them as a menu. I will include screenshots to visually explain what I'm trying to do as well.
Does anyone have any ideas on how to check if that layer of objects has children, and if so add an arrow (or anything) to indicate this?
Here is my code:
class Menu extends React.Component {
state = {
categories: [],
objectKeys: null,
tempKeys: []
};
makeMenuLayer = layer => {
const { objectKeys } = this.state;
const layerKeys = Object.entries(layer).map(([key, value], index) => {
return (
<ul key={key}>
<div onClick={() => this.handleShowMore(key)}>{key}</div>
{objectKeys[key] && this.makeMenuLayer(value)}
</ul>
);
});
return <div>{layerKeys}</div>;
};
handleShowMore = key => {
this.setState(prevState => ({
objectKeys: {
...prevState.objectKeys,
[key]: !this.state.objectKeys[key]
}
}));
};
initializeTempKeys = layer => {
Object.entries(layer).map(([key, value]) => {
const newTempKeys = this.state.tempKeys;
newTempKeys.push(key);
this.setState({ tempKeys: newTempKeys });
this.initializeTempKeys(value);
});
};
initializeObjectKeys = () => {
const { tempKeys } = this.state;
let tempObject = {};
tempKeys.forEach(tempKey => {
tempObject[tempKey] = true;
});
this.setState({ objectKeys: tempObject });
};
componentDidMount() {
axios.get("https://www.ifixit.com/api/2.0/categories").then(response => {
this.setState({ categories: response.data });
});
const { categories } = this.state;
this.initializeTempKeys(categories);
this.initializeObjectKeys();
this.setState({ categories });
}
render() {
const { categories } = this.state;
return <div>{this.makeMenuLayer(categories)}</div>;
}
}
Here is how it currently looks, and I'd like it so any element that has more elements within it have an arrow or something to show there is more data nested (so for this, Apparel, Accessory, Clothing, etc would have arrows):
Here's an example of the type of thing I'm going for:
来源:https://stackoverflow.com/questions/56086870/how-to-check-if-nested-objects-have-children-or-not