如何在Semantic React UI Card的onClick中传参并解决JSON循环错误?
Hey there! Let's break down what's going on here and get your card clicks routing to the correct detail page without that annoying JSON error.
Why the "Circular Structure" Error Happens
Semantic UI React's Card component passes a data object to the onClick handler that includes internal component references—creating a circular structure (think: an object that references itself indirectly). When you try to JSON.stringify(data), JavaScript throws that error because it can't serialize circular references. The good news? You don't need this entire data object anyway—you only care about contentId.
Simple Solution: Pass contentId Directly
Since you're already mapping over your article data and have access to contentId (from article.key), you can skip relying on the Card's data parameter entirely. Just pass contentId directly to your handleOnClick function.
Modified Code Snippets
First, update the Card's onClick handler in your newsArticles method:
const cards = this.props.content.data.map( article => { let contentId = article.key; return ( <Grid.Column stretched key={contentId}> {/* Add key to Grid.Column for proper React list rendering */} <Card key={contentId} onClick={ (event) => this.handleOnClick(event, contentId)} style={{ marginBottom: '2em'}} > <Image src={this.props.auth.data.sfInstanceUrl + article.image} /> <Card.Content> <Card.Header> {article.title} </Card.Header> <Card.Description> {article.excerpt} </Card.Description> </Card.Content> </Card> </Grid.Column> ); });
Then, update your handleOnClick function to use the direct contentId parameter:
handleOnClick( event, contentId ) { // Prevent default browser behavior if necessary event.preventDefault(); // Use contentId to fetch the specific article from your Redux store const selectedArticle = this.props.content.data.find(article => article.key === contentId); // Example: Navigate to the detail page (adjust the route to match your app's structure) this.props.history.push(`/article-detail/${contentId}`); // Optional: Dispatch a Redux action to set the selected article in your store for the detail page // this.props.dispatch(setSelectedArticle(selectedArticle)); console.log(`Selected article ID: ${contentId}`); }
Why This Works
- No more circular structure errors: We're completely avoiding the problematic
dataobject from the Card component. - Cleaner, more focused code: We only pass the exact value we need (
contentId), making the handler logic simpler. - Easy integration with Redux & routing: You can immediately use
contentIdto filter your store data and navigate to the detail page.
内容的提问来源于stack exchange,提问作者adam.sellers

