React:从json文件渲染单引号

时间:2017-05-20 09:46:43

标签: json reactjs

我有新的反应,并想知道"对"是什么?在组件安装时将json文件中的引用呈现给页面的方法。

我试过这个,但有时它会拉出所有引号并将它们全部呈现在页面上。

import React, { Component } from 'react';
import * as Quotes from '../utils/quotes';

class Home extends Component {

    getRandomQuote () {
      let keys = Object.keys(Quotes)
      return Quotes[keys[keys.length * Math.random() << 0]];
    }

    render () {
        return (
            <div>
                <div className="PageContainer">
                    <h1>Welcome</h1>
                    <div id="quotes">Here is a quote for you:<p id="quote_text">{this.getRandomQuote()}</p></div>
                </div>
            </div>
        );
    }
}

这是演示JSON文件内容的简短部分:

[
  "Life isn’t about getting and having, it’s about giving and being. - Kevin Kruse",
  "Whatever the mind of man can conceive and believe, it can achieve. - Napoleon Hill",
  "Strive not to be a success, but rather to be of value. - Albert Einstein"
]

1 个答案:

答案 0 :(得分:2)

您粘贴的内容为array,因此您无需使用Object.keys。使用Math.random()直接生成随机索引并返回结果。

写下这样的函数:

getRandomQuote() {
  return Quotes[(Quotes.length * Math.random()) << 0];
}

检查工作代码段:

let Quotes = ["Life isn’t about getting and having, it’s about giving and being. - Kevin Kruse",
    "Whatever the mind of man can conceive and believe, it can achieve. - Napoleon Hill",
    "Strive not to be a success, but rather to be of value. - Albert Einstein"
]

let i = Quotes.length;

function getRandomQuote() {
    return Quotes[(Quotes.length * Math.random()) << 0];
}

while(i--)
   console.log(getRandomQuote());