React Redux:如何从状态中获取随机对象

React Redux: How to get a random object from state

我是 React Redux 的新手。我试图从状态(对象数组)中获取一个随机对象。我通过 action creator 获取数据,并使用 lodash 打乱对象。我还使用 slice 来限制对象的数量。我也打算在另一个组件上使用这些相同的对象。

以下是我的操作:

import _ from 'lodash';

export const fetchItems = () => async dispatch => {
  const response = await fetch("http://jsonplaceholder.typicode.com/photos") // fetch 5000 items
  const data = await response.json();

  dispatch({ type: 'FETCH_ITEMS', payload: _.shuffle(data.slice(0, 8)) })
}

为了从状态中获取随机对象,我使用 Math.random 生成一个随机数并使用它来访问对象数组。但是下面的代码给我一个错误:this.props.news[Math.floor(...)] is undefined

import React from 'react';
import { connect } from 'react-redux';
import { fetchItems } from '../actions';

class Title extends React.Component {
  componentDidMount() {
    this.props.fetchItems();
  }

  renderList() {
     return (
       <h2>{this.props.data[Math.floor(Math.random() * this.props.data.length)].title}</h2>
     )
 }

  render() {
    return (
      <div className="jumbotron">
        {this.renderList()}
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { data: state.data }
}

export default connect(mapStateToProps, { fetchItems: fetchItems })(Title);

如何在 Title 组件上获取随机对象?

error: this.props.news[Math.floor(...)] is undefined 只是说在 some “随机”索引处没有定义的值可以从中访问 title 属性 的.

我的猜测是 props.data 最初是空的。您可以使用可选链接来防止未定义的访问,this.props.data[randomIndex]?.title.

renderList() {
  const randomIndex = Math.floor(Math.random() * this.props.data.length);
  return (
    <h2>{this.props.data[randomIndex]?.title}</h2>
  )
}

如果您无法使用可选链接,则应用保护子句。

renderList() {
  const randomIndex = Math.floor(Math.random() * this.props.data.length);
  return (
    <h2>{this.props.data[randomIndex] && this.props.data[randomIndex].title}</h2>
  )
}