gpt4 book ai didi

javascript - 在 react 中从 json 字符串渲染 HTML

转载 作者:数据小太阳 更新时间:2023-10-29 04:19:03 35 4
gpt4 key购买 nike

我正在尝试根据从 API 接收到的 JSON 字符串呈现 HTML 对象。我能够让字符串成功呈现为 HTML,但它显示了整个 JSON 字符串。我只想获取特定值(电话、姓名、ID)。从我的 JSON 数组中提取特定值并将其格式化为 HTML 的最佳方法是什么?我指的是按州记录,但我无法在呈现过程中获得记录的任何子值。

Here is the JSON result rendered to HTML I'm getting when running the below code.

class menuScreen extends React.Component {

constructor(props) {
super(props)

const data = store.getState();

this.state = {



username: '',
messages: data.messages
}
}

handleSearch(e) {
this.setState({username: e.target.value})
}

handleChange(evt) {
this.setState({
username: evt.target.value.substr(0, 100)
});

}

onLinkClicked() {

var conn = new jsforce.Connection({serverUrl: 'https://cs63.salesforce.com', accessToken: sessionStorage.getItem('token')})

var parent = this.state.username
//console.log(this.state.username)
conn.sobject("Contact").find({
LastName: {
$like: parent
}
}, 'Id, Name, Phone'

).sort('-CreatedDate Name').
limit(5).skip(10).execute(function(err, records) {
if (err) {
return console.error(err);
}
for (var i = 0; i < records.length; i++) {
var record = (records[i]);
console.log("Name: " + record.Name); //these are the records I'm trying to render
console.log("Phone: " + record.Phone);


} this.setState({records : records})


}.bind(this));

}

render() {
return (
<div className='menubox' id='menubox'>
<div className='searchbar-container'>
<form onSubmit={e => e.preventDefault()}>
<input type='text' size='25' placeholder='Contact Last Name' onChange={this.handleChange.bind(this)} value={this.state.username}/>
<button type='submit' onClick={this.onLinkClicked.bind(this)}>
Search
</button>
</form>
</div>
<div>
<div dangerouslySetInnerHTML={ { __html: JSON.stringify(this.state.records) } }></div> //how can I show specific values, isntead of the entire string?
</div>
</div>
)
}
}
export default menuScreen;

最佳答案

JSON.parse 将您的字符串转换为 JavaScript 对象。然后,您可以对该对象执行任何您想要的处理,例如删除您不需要的字段,然后您可以将其JSON.stringify 返回为您可以呈现的 JSON 字符串。

类似于:

class BlahBlah extends React.Component {
constructor() {
//...some code...
this.processJson = this.processJson.bind(this)
}
//...a lot of code...
processJson(json) {
var object = JSON.parse(json)
var output = {}
//for every property you want
output[property] = object[property]
return JSON.stringify(output)
}
//...a lot more code...
render() {
return(
//...even more code...
<div dangerouslySetInnerHTML={ { __html: this.processJson(this.state.records) } }></div>
//...and yet more code.
)
}
}

关于javascript - 在 react 中从 json 字符串渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327766/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com