【问题标题】:div from method is not rendering on the User Interface in react js来自方法的 div 未在反应 js 的用户界面上呈现
【发布时间】:2021-03-09 21:01:38
【问题描述】:

我正在使用 react js 并尝试从 holdingsByAccounts 属性中访问一些虚拟数据。页面加载时,问题 jsx 未呈现到屏幕上。一直在寻找其他方式和其他有这种情况的网站。所以我的代码如下:

  class PortDashSideBar extends Component {
              constructor(props) {
                super(props);
                this.oldPortfolioValue = 0;
              }
            
      getHoldingsForAccount = (id) => {
        this.props.holdingsByAccount.map((holding) => {
          return <span>{holding[id].value}</span>;
        });
      }
    
            
            
              renderConfigurations = () => {
                const {
                  classes,
                  accounts,
                  holdingsByAccount,
                  holdingsByAsset,
                  currentAccountId,
                  actions,
                  user
                } = this.props;
            
                const animationClassGreen = 'animateChangeGreen';
                const animationClassRed = 'animateChangeRed';
            
            
                
            
                return (
                  <Table className={classes.table} name="myConfigurations">
                    <TableBody style={{ display: 'flex', flexDirection: 'column' }}>
                      {
                        accounts.map(account => (
                          <ButtonBase>
                            <TableRow
                              hover
                              name={account.name}
                              key={account.id}
                              onClick={() => { actions.updateAccount(account.id); }}>
                              <TableCell className={classes.cellBotIcon} />
                              <TableCell className={classes.cellName}>
                                <Typography className={classes.botName}>
                                  {account.label}
                                </Typography>
                                <Typography>
                                  <svg className={classes.svg}>
                                    <img src="https://yt3.ggpht.com/ytc/AAUvwngo7rox3GTqcW5Omxr-UGXHwmGO4To3QDygqaYxpg=s900-c-k-c0x00ffffff-no-rj" />
                                  </svg>
                                  <span className={classes.configName}>
                                    {this.getHoldingsForAccount(account.id)}
                                  </span>
                                </Typography>
                              </TableCell>
                            </TableRow>
                          </ButtonBase>
            
                        ))
                      }
                    </TableBody>
                  </Table>
                );
              }
            
              render() {
                const {
                  classes
                } = this.props;
            
                return (
                  <Paper className={classes.paper} elevation={0} square >
                    <Grid container alignItems="center" justify="center">
                      <Grid className={classes.configurations} xs={12} item>
                        {this.renderConfigurations()}
                      </Grid>
                    </Grid>
                  </Paper>
                );
              }
            }
            
            PortDashSideBar.defaultProps = {
            };
            
            PortDashSideBar.propTypes = {
              actions: PropTypes.object.isRequired,
              classes: PropTypes.object.isRequired,
              accounts: PropTypes.array.isRequired,
              holdingsByAccount: PropTypes.array.isRequired,
              holdingsByAsset: PropTypes.array.isRequired,
              currentAccountId: PropTypes.string.isRequired,
              user: PropTypes.object.isRequired
            };
            
            
            function mapStateToProps(state) {
              return {
                user: state.global.user.user,
                holdingsByAccount: state.holdings.holdings.byAccount,
                holdingsByAsset: state.holdings.holdings.byAsset,
                holdingsLoaded: state.holdings.holdings.holdingsLoaded,
                accounts: state.global.accounts.accounts,
                currentAccountId: state.trade.interactions.currentAccountId,
              };
            }
            
            function mapDispatchToProps(dispatch) {
              return {
                actions: {
                  ...bindActionCreators({
                    updateAccount,
                  }, dispatch)
                }
              };
            }
            
            export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(PortDashSideBar));

现在,它没有显示错误,但也没有在屏幕上呈现

【问题讨论】:

  • 您确定holdingsByAccount 中的每个持股对accounts 中的每个帐户都有价值吗?
  • 是的,我刚刚检查过
  • 你需要更改getHoldingsForAccount方法,你应该通过id找到记录,你试图通过索引找到它,试试this.props.holdingsByAccount.find(({id : holdingId }) => holdingId === id),这样你就可以渲染正确的持有物品了。

标签: javascript json reactjs react-native asynchronous


【解决方案1】:

为了给你一个答案,我认为这是因为你试图通过索引访问数组项,而不是通过项 id,考虑一下:

const array = [1,2,3]
console.log(array[3])
// Prints undefined because the index starts in 0, so the index 3 should be the 4th item which does not exist in this array

因此,您的示例正在尝试访问不存在的索引,这就是崩溃的原因。另外值得一提的是,您的对象 id 属性是基于您上传的图像的字符串,因此如果该字符串不是数字,它也会失败:

const array = [1,2,3]
console.log(array["1"])
// Prints 2 because it parses the string to a number

const array = [1,2,3]
console.log(array["an-id"])
// Prints undefined because the string can't be parsed to a number

所以为了让事情顺利进行,请将代码更改为:

getHoldingsForAccount = (id) => {
 // Use Array.find to find the item that matches the id parameter provided by the function
 const holding = this.props.holdingsByAccount.find((item) => item.id === id)

 // Returns the JSX only if the match was found.
 return holding && (
  <span>{holding.value}</span>
 )
}

【讨论】:

  • 您好,谢谢您的帮助。该应用程序不再崩溃,但由于某种原因,该 div 未在用户界面上呈现。似乎一切都很好,除了它没有在屏幕上呈现的简单事实
  • 帐户数组看起来如何?可以发一下吗?
  • 嘿,我刚刚编辑了帖子以显示它的结构。谢谢
  • 您是否在 getHoldingsForAccount 中返回 JSX?如果是这样,如果您在该函数中使用 console.log(holding) 会发生什么
  • 再次感谢您的回复。我已经更新了帖子以显示功能的图像和持有的控制台
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2022-12-16
相关资源
最近更新 更多