如何在我的 React 组件中显示从 redux 中获取的 json?

How to display the fetched json from redux in my react component?

我的 redux 商店中有以下诗歌 json:

poems: {
'5a0f3367af648e17fa09df5d': {   //this is my poem id
  _id: '5a0f3367af648e17fa09df5d', //this is also the same as above
  title: 'my first poem',
  text: 'some lorem ipsum long text ',
  userId: '5a03f045995c0f5ee02f9951',  //this is my user id
  __v: 0
},
'5a0ff2a5b4a9591ecb32d49c': {
  _id: '5a0ff2a5b4a9591ecb32d49c',
  title: 'my second poem',
  text: 'some lorem ipsum long text',
  userId: '5a03f045995c0f5ee02f9951',  //this is the same user id as above
  __v: 0
}


}

现在如何在我的 React 组件中显示每首诗的标题和文本。这里我只有 2 首诗和 poems id 。但诗歌的数量可能因用户不同而不同。所以基本上我需要一种方法将这些诗歌从我的 redux 商店获取到我的组件然后渲染它们。

您可以使用 react-redux 中的 connect 来获取 react-redux state 的内容并将它们作为 props 传递到 react 组件中

import React from 'react';
import _ from 'lodash';
import {connect} from 'react-redux';

class Poems extends React.Component {
    render(){
       return (
           <div>
               //poems from state will be passed as props to this component
               {_.map(this.props.poems, poem => {
                   return (
                       <div>
                          <div>{poem.title}</div>
                          <div>{poem.text}</div>
                       </div>
               )}
           </div>
       );
    }
}

const mapStateToProps = (state) => ({
   poems: getPoems(state);    //method to get poems from redux state
});

export default connect(mapStateToProps)(Poems);