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