如何渲染嵌套数组对象?需按指定boardId渲染对应widgetList
No problem, let's walk through how to render each widgetList tied to its parent board using your this.props.storyboard structure. Here's a step-by-step implementation tailored to React (since you're using this.props):
Step 1: Break Down the Data Structure
First, confirm we're accessing the right layers:
this.props.storyboard.boardList: Array of board objects, each with a uniqueboardIdand its ownwidgetList- Each
board.widgetList: Array of widget objects belonging exclusively to that board
Step 2: Implement the Render Logic
We'll create reusable helper methods to render individual boards and widgets, then map over the boardList to render everything in a structured way.
Example Class Component Implementation
class StoryboardRenderer extends React.Component { // Helper to render a single widget with its properties renderWidget = (widget) => { // Customize this JSX to match your widget's UI requirements return ( <div key={widget.widgetId} className="widget-card"> <h3>{widget.widgetName}</h3> <p>Widget Type: {widget.widgetType}</p> <p>Left Target Value: {widget.leftTargetValue}</p> {/* Add other widget fields (like rightTargetValue) as needed */} </div> ); }; // Helper to render a board and its associated widgets renderBoard = (board) => { return ( <div key={board.boardId} className="board-container"> <h2>{board.boardTitle}</h2> <p>Last Updated: {new Date(board.modifiedAt).toLocaleString()}</p> // Handle empty widget lists gracefully {board.widgetList && board.widgetList.length > 0 ? ( <div className="widget-grid"> {board.widgetList.map(this.renderWidget)} </div> ) : ( <p>No widgets added to this board yet.</p> )} </div> ); }; render() { const { storyboard } = this.props; // Handle missing or empty board data if (!storyboard?.boardList || storyboard.boardList.length === 0) { return <p>No boards available to display.</p>; } return ( <div className="storyboard-wrapper"> {storyboard.boardList.map(this.renderBoard)} </div> ); } }
Key Details to Note:
- Unique Keys: Always use unique identifiers (
boardId,widgetId) as thekeyprop when mapping arrays in React—this ensures efficient DOM updates and avoids rendering errors. - Null Safety: We added checks like
storyboard?.boardList(optional chaining) andboard.widgetList && board.widgetList.length > 0to prevent crashes if data is incomplete or missing. - Customization: Adjust the
renderWidgetJSX to match your actual widget needs (e.g., render a dedicated Venn diagram component ifwidgetTypeis "venn").
Step 3: Usage
Simply pass your storyboard prop to the component wherever you need to render it:
<StoryboardRenderer storyboard={this.props.storyboard} />
If you're using functional components with hooks, the logic is nearly identical—you'll just replace class methods with regular functions and use props directly instead of this.props.
内容的提问来源于stack exchange,提问作者R9102

