首页 > 解决方案 > React&Redux:我在后台有状态,但无法在我的 JSX 中呈现循环数组

问题描述

到目前为止,我已经GET_TOURNAMENTS将所有锦标赛对象设置为我的状态,并在页面上呈现它们。

然后,我给每个锦标赛一个调用按钮,该按钮showTournament()选择我点击的任何锦标赛,并更新状态。当我点击SHOW_TOURNAMENT我的状态看起来像:

tournament
  tournaments: [{...}, {...}]           <<~~this is from GET_TOURNAMENTS
  showTournament: {                     <<~~begins as (showTournament: "") until showTournament() action
    _id: "etc",
    title: "Tournament One",
    status: "Open",
    participants: [                          <<~~an array of User objects
      0: {_id: "asdf", username: "asdf"},
      1: {_id: "asdf", username: "asdf"}
    ]
  }

Annnnnnnnd 我试图通过执行以下操作在我的 ShowTournament 组件中呈现所有这些:

class TournamentShow extends Component {
    static propTypes = {
        tournament: PropTypes.object.isRequired,
        auth: PropTypes.object.isRequired
    };

    render() {
        const { _id, title, hostedBy, status, participants } = this.props.tournament.showTournament;

        return (
            <div>
                <h1>{ title }</h1>
                <p>status: { status }</p>
                <p>Registered Participants:</p>
                {
                    participants ?
                    participants.forEach(participant => {
                        return (
                            <ul>
                                <li>{participant}</li>
                            </ul>
                        )
                    }) :
                    null
                }
                <p>Hosted by: { hostedBy }</p>
                <Link to="#">Sign Up</Link><br/>
                <Link to="/">Back to Tournaments main page</Link>
            </div>
        )
    }
};

const mapStateToProps = state => ({
    tournament: state.tournament,
    auth: state.auth
});

export default connect(mapStateToProps, { showTournament })(TournamentShow);

这说明什么。即使数组中有参与者,也不会呈现任何内容。

我也尝试过简单 <<~~ 编辑:我一开始有标签,把它们放在 {} 之外

                <p>Registered Participants:</p>
                <ul>
                  {
                      participants.forEach(participant => {
                          return (
                              <li>{participant}</li>
                          )
                      })
                  }
                </ul>

我得到错误TypeError: Cannot read property 'forEach' of undefined

渲染中的所有非数组数据showTournament都很好。我发现了其他 Stack Overflow 问题并尝试了许多解决方案,但其他问题完全不同,以至于我无法弄清楚如何获得正确的实现。

谢谢大家!

标签: javascriptreactjsreduxmern

解决方案


1)你需要使用map,因为forEach不返回任何东西,所以你返回的任何东西forEach对外部世界都是不可见的forEachmap将返回一个数组。

2)你想做什么{participant}?它是一个对象,所以要么使用打印它,要么JSON.stringify(participant)更好,打印_idusername单独打印,如下所示:

participants.map(participant => 
   (
      <ul>
         <li>{participant._id}</li>
         <li>{participant.username}</li>
      </ul>
   )
)

3)如果您如您所说遇到错误,那么很可能participantsundefined. 您可以尝试调试并查看其值是否已填充。如果无法调试,只需尝试使用打印它

<div>{JSON.stringify(participants)}</div>

甚至

<div>{JSON.stringify(this.props.tournament.showTournament)}</div>

推荐阅读