【问题标题】:Render HTML from a json string in react在反应中从 json 字符串渲染 HTML
【发布时间】:2017-09-05 18:26:54
【问题描述】:

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

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;

【问题讨论】:

  • record.Name 更改为 record.attributes.Name

标签: javascript json reactjs render


【解决方案1】:

您可以运行一个映射函数并为每个项目输出 JSX。

class menuScreen extends React.Component {

    constructor(props) {
        super(props)

        const data = store.getState();

        this.state = {
            username: '',
            messages: data.messages,
            records: [],
        };
    }

    render() {
        return (
            <div>
                {this.state.records.map(record => (
                    <div>{record.attributes.name} {record.attributes.phone} {record.whatever}</div>
                )}
            </div>
        );
    }
}

请记住,如果您想在 map 函数中使用更复杂的 HTML 结构,则必须将其包装在单个 DOM 节点中。

完整的文件如下所示:

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>
                {this.state.records.map(record => (
                    <div>{record.attributes.name} {record.attributes.phone}</div>
                )}
            </div>
        </div>
    );
}

【讨论】:

  • 我尝试使用 map 函数,但出现错误:“无法读取未定义的属性 'map'”。我不知道为什么,我可以用这个
    来引用记录
  • 安装组件时未定义记录。只需将默认数组添加到您的构造函数。 dangerouslySetInnerHTML 发生的事情是,它最初渲染字符串“未定义”,然后渲染 JSON 字符串。
【解决方案2】:

您可以创建一个单独的渲染方法来渲染您的记录,如下所示:

renderRecords(records) {
  return records.map(r => <div> r.Name, r.Phone</div>);
}

然后在你的渲染方法中调用该方法,而不是像这样使用危险的SetInnerHTML

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>{ this.renderRecords() }</div> 
    </div>
</div>
    )
}

【讨论】:

    【解决方案3】:

    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.
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2012-08-20
      • 1970-01-01
      • 2021-01-30
      • 2020-06-12
      • 2017-03-21
      • 2011-07-26
      • 2016-11-13
      • 1970-01-01
      相关资源
      最近更新 更多