【问题标题】:How to display the fetched json from redux in my react component?如何在我的反应组件中显示从 redux 获取的 json?
【发布时间】:2018-05-02 15:17:00
【问题描述】:

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

【问题讨论】:

标签: json reactjs redux react-redux render


【解决方案1】:

您可以使用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);

【讨论】:

  • @SurajSharma,很高兴它解决了您的问题。如果您认为这是正确的,您可能想要对此进行投票并在此答案上打勾。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2021-01-11
  • 1970-01-01
相关资源
最近更新 更多