1

我是 React Redux 的新手。我正在尝试从状态(对象数组)中获取一个随机对象。我通过动作创建器获取数据,并使用 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 组件上获取随机对象?

4

1 回答 1

1

error: this.props.news[Math.floor(...)] is undefined只是说在某个“随机”索引处没有定义的值可以访问其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>
  )
}
于 2021-04-30T06:00:18.087 回答