React对接WordPress GraphQL:无法渲染Location名称问题
解决律师Location名称无法渲染的问题
你的问题出在locations.edges是一个数组,不能直接通过locations.edges.node.name访问单个位置名称,必须遍历数组中的每一项来获取每个位置的node.name。
修改步骤:
- 找到代码中这行错误的代码:
<p>{locations.edges.node.name} I want the locations.name here</p>
- 替换为遍历
edges数组的写法,根据需要选择展示格式:
方式1:用逗号分隔显示所有位置
<p>Locations: {locations.edges.map(edge => edge.node.name).join(', ')}</p>
方式2:用列表展示每个位置
<div> <p>Locations:</p> <ul> {locations.edges.map((edge) => ( <li key={edge.node.id}>{edge.node.name}</li> ))} </ul> </div>
完整修改后的displayContent函数示例:
function displayContent() { /* dangerously set for hiding elements */ const { loading, error, data } = useQuery(POSTS_QUERY); if (loading) return <p>Loading...</p>; if (error) return <p>Error...</p> return data.lawyers.nodes.map(({ name, credentials, profilePhoto, bio, practicingSince, locations }) => ( <div key={name}> {/* 添加唯一key,避免React警告 */} <Container> <Row> <Col className="backCard"> <h1 className="titlePost">{name}</h1> <p className="credentials">{credentials}</p> <img className="workplace" src={profilePhoto.mediaItemUrl} alt={profilePhoto.altText} /> {/* 添加alt属性,符合语义化 */} <p className="credentials">Bio</p> <p dangerouslySetInnerHTML={{ __html: bio }} className="increaseMargin"></p> <p>Practicing since : {practicingSince}</p> <Link to="/locations" style={{ textDecoration: 'none' }}>Locations</Link> {/* 替换为正确的遍历写法 */} <p>Locations: {locations.edges.map(edge => edge.node.name).join(', ')}</p> </Col> </Row> </Container> </div> )); }
额外提示:
- 给每个遍历的元素添加唯一
key属性(比如用律师姓名或ID),避免React控制台警告。 - 给图片添加
alt属性,提升页面可访问性。
内容的提问来源于stack exchange,提问作者user19102549
相关产品推荐
相关产品推荐

