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

时间:2017-11-19 07:01:49

标签: json reactjs redux react-redux render

我的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首诗歌和诗歌。但诗歌的数量可能因用户不同而有所不同。所以基本上我需要一种方法将这些诗从我的redux商店中获取到我的组件然后渲染它们。

1 个答案:

答案 0 :(得分:1)

您可以使用react-redux中的connect来获取react-redux状态的内容,并将其作为反应组件中的道具传递

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);