【问题标题】:React Redux: How to get a random object from stateReact Redux:如何从状态中获取随机对象
【发布时间】:2021-07-23 11:59:23
【问题描述】:

我是 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 组件上获取随机对象?

【问题讨论】:

    标签: arrays reactjs redux lodash


    【解决方案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>
      )
    }
    

    【讨论】:

    • 谢谢!你的解决方案奏效了。我试过if(!this.props.news) return null;,以防数据没有准备好,但似乎这不是解决空状态问题的正确方法......
    • @kayak 对,是的,[] 是一个真实定义的对象。
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    相关资源
    最近更新 更多