猿问

为 React 中的每个对象渲染 json 对象名称/描述

在这里反应新手。我有一个组件,它以 JSON 格式获取一组对象并将其保存到状态中。


我现在不确定如何在组件渲染函数中渲染每个对象的名称/描述。


有任何想法吗?


https://codesandbox.io/s/admiring-ishizaka-rfp3k - 演示


   return (

      <div className="App">

        {name1} // Object 1 name

        {description1} // Object 1 description

        {name2} // Object 2 name

        {description2} // Object 2 description

      </div>

    );


ABOUTYOU
浏览 192回答 3
3回答

千巷猫影

您应该使用 map 遍历对象的配置文件数组:<div className="App">&nbsp; &nbsp; &nbsp; &nbsp; {this.state.profiles.map((profile, index) =>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{profile.name}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{profile.description}</p>&nbsp; &nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; &nbsp; &nbsp; <br/>&nbsp; &nbsp; &nbsp; </div>关于地图功能的更多细节:https : //reactjs.org/docs/lists-and-keys.html

翻翻过去那场雪

您需要遍历数据(即对象数组)并使用您所需的对象属性呈现它们。添加一个返回 JSX 以渲染配置文件数据的方法:renderProfiles = () => {&nbsp; &nbsp; const profiles = this.state.profiles || [];&nbsp; &nbsp; const renderProfiles = profiles.map(profile => (&nbsp; &nbsp; &nbsp; &nbsp; <div key={profile.mainCompanyID}> // pass unique id as a key value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {profile.name}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {profile.description}&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; ));&nbsp; &nbsp; return renderProfiles;};然后将其添加到您的主要渲染方法中:render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; {this.renderProfiles()}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );}完整的代码和框链接 - https://codesandbox.io/s/elastic-sara-qjc7r

侃侃无极

您可以创建一个方法并从渲染调用它:&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; {this.renderProfiles()}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }&nbsp; renderProfiles = () => {&nbsp; &nbsp; return this.state.profiles.map((profile)=>{&nbsp; &nbsp; &nbsp; const {name,description} = profile;&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; &nbsp; {name}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {description}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; })&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答