如何在React中从数组中呈现随机对象?

时间:2016-06-29 13:46:18

标签: javascript random reactjs

我刚开始在工作中学习React,我需要使用React构建一个博客。我需要将随机帖子显示为“推荐帖子”,在做了一些研究后我发现了一个可能的解决方案,使用Math.random()但我无法弄清楚如何在我的组件中实现它。

这是我的代码:

RecommendedPost / index.js

import React from 'react';
import { Link } from 'react-router';

class RecommendedPosts extends React.Component {

render() {
return (
  <ul>
    {this.props.posts.map((post, idx) => {
      return (
        <li key={idx}>
          <p>{post.title}</p>
          <p>{post.text}</p>
          <p>{post.category}</p>
          <Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
        </li>
      );
    })}
  </ul>
);
}
}
RecommendedPosts.propTypes = {
posts: React.PropTypes.array,
};
export default RecommendedPosts;

然后我在我的容器中使用这个组件: BlogPage / SinglePostPage / index.js

import React from 'react';
// ...other imported stuff
import RecommendedPosts from 'components/Blog/RecommendedPosts';

class PostPage extends React.Component {

render() {
  // dummy-recomended-posts
const posts = [
  {
    id: 1,
    title: 'How to Cook Blue Meth',
    description: 'Lorem ipsum dolor sit amet, turpis at, elit',
    thump: 'thump.jpg',
    hero: '/img/',
    category: 'k1',
    fullname: 'Walter White',
    published: '10.05.2016, 15:30pm',
  },
  {
    id: 2,
    title: 'Passenger',
    description: 'Lorem ipsum dolor sit amet, turpis at, elit',
    thump: 'thump.jpg',
    hero: '/img/',
    category: 'k2',
    fullname: 'Chino Moreno',
    published: '10.05.2016, 15:30pm',
   },
    // ...and more dummy posts(about 7)
   ];
return (
   <div>
   // here, I pass the posts array to my component
   <RecommendedPosts posts={posts} />
   </div>
  );
  }
 }
}
export default connect(null, mapDispatchToProps)(PostPage);

我的想法是使用id作为ref来随机渲染帖子,但我又找不到方法。

希望有人可以帮助我,如果答案对每个人来说都太明显,那就很抱歉。

3 个答案:

答案 0 :(得分:8)

我继续为你创造了一个实用的例子

import React from 'react';
import { Link } from 'react-router';

function shuffleArray(array) {
  let i = array.length - 1;
  for (; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

class RecommendedPosts extends React.Component {
  render() {
    const shuffledPosts = shuffleArray(this.props.posts);
    return (
      <ul>
        {shuffledPosts.map((post, idx) => {
          return (
            <li key={idx}>
              <p>{post.title}</p>
              <p>{post.text}</p>
              <p>{post.category}</p>
              <Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
            </li>
          );
        })}
      </ul>
    );
  }
}
RecommendedPosts.propTypes = {
  posts: React.PropTypes.array,
};
export default RecommendedPosts;

额外提示 - 由于您没有使用状态或生命周期,因此您可以创建一个更简单的功能组件:

import React from 'react';
import { Link } from 'react-router';

function shuffleArray(array) {
  let i = array.length - 1;
  for (; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

function RecommendedPosts({ posts }) {
  const shuffledPosts = shuffleArray(posts);
  return (
    <ul>
      {shuffledPosts.map((post, idx) => {
        return (
          <li key={idx}>
            <p>{post.title}</p>
            <p>{post.text}</p>
            <p>{post.category}</p>
            <Link to={`/blog/post-1/:${post.id}`}>Weiter lesen</Link>
          </li>
        );
      })}
    </ul>
  );
}
RecommendedPosts.propTypes = {
  posts: React.PropTypes.array,
};
export default RecommendedPosts;

答案 1 :(得分:3)

在推荐的帖子中,首先将帖子随机播放并将其存储在状态中,然后呈现

<header>
    <div class="navbar">
        <ul>
            <li style="float: left"><a href="#home">Home</a></li>
            <li><a href="#contact">Contracts</a></li>
            <li><a href="#about">About Us</a></li>
            <li><a href="#other">Other</a></li>
            <li> <a href="#release">Release Notes</a></li>
            <li> <a target="_blank" href="http://www.phpartnership.com">Pinnacle Health Partnership</a></li>
        </ul>
        <ul class="aditional">
				<li><a href="#green">So this would have a Green underline</a></li>
               <li><a href="#blue">So this would have a Blue underline</a></li>
                <li><a href="#red">So this would have a Red underline</a></li>
                <li><a href="#orange">So this would have a Orange underline</a></li>
               </ul>
    </div>
</header>

答案 2 :(得分:1)

你可以使用lodash shuffle函数随机化你的数组,然后通过从该数组中获取数据来进行渲染。