Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何通过多个数组和条件渲染组件进行映射_Javascript_Reactjs - Fatal编程技术网

Javascript 如何通过多个数组和条件渲染组件进行映射

Javascript 如何通过多个数组和条件渲染组件进行映射,javascript,reactjs,Javascript,Reactjs,现在我正在开发一个react博客类型的应用程序,目前我在尝试找出解决问题的最佳方法时遇到了一些问题。现在我有一个postbody组件,它使用从redux检索到的数据将props从redux发送到postbody模板组件。现在它通过一个叫做positems的常量映射。我有一个函数,它返回与使用的post Id相同的注释。我需要完成的是,一旦它映射到post body模板,如果有具有相同post id的注释,它就可以在相同的postBodyTemplate组件中显示这些注释 对于我的PostBody

现在我正在开发一个react博客类型的应用程序,目前我在尝试找出解决问题的最佳方法时遇到了一些问题。现在我有一个postbody组件,它使用从redux检索到的数据将props从redux发送到postbody模板组件。现在它通过一个叫做positems的常量映射。我有一个函数,它返回与使用的post Id相同的注释。我需要完成的是,一旦它映射到post body模板,如果有具有相同post id的注释,它就可以在相同的postBodyTemplate组件中显示这些注释

对于我的PostBody组件,我有:

import React, { Component, useState, useEffect } from 'react';
import PostBodyTemplate from './postBodyTemplate';
import PropTypes from 'prop-types'
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/postActions';
import { fetchComments } from '../actions/commentActions';
import axios from 'axios';

class PostBody extends Component {

  componentWillMount(){
    this.props.fetchPosts();
    // this.props.fetchComments();
}

render() {




 const reversedProps = this.props.posts.reverse();

var activeComments = [];
const getComments = async (id) => {
  const response = await axios.get("http://10.6.254.22:5000/comments/" +id);
  if (response.data.length > 0) {
    console.log(response.data);
    activeComments.push(response.data)
    return response.data
    //  activeComments = response.data;
  }
};

const postIdMap = post => post.id;
const postIds = reversedProps.map(postIdMap);
console.log(postIds);
// console.log(commentIds);

postIds.map(getComments);


  const postItems = reversedProps.map(post => (

      <PostBodyTemplate key={post.id} title={post.title} postBody={post.postBody} giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName}/>

  ));



  return (
      <div>
         <h1>{postItems}</h1>
      </div>
  )
}
}

PostBody.propTypes = {
  fetchPosts: PropTypes.func.isRequired,
  posts: PropTypes.array.isRequired,
  fetchComments: PropTypes.func.isRequired,
  // comments: PropTypes.array.isRequired
}

const mapStateToProps = state =>({
  posts: state.posts.items,
  // comments: state.comments.items
})

export default connect(mapStateToProps, { fetchPosts, fetchComments })(PostBody);
我希望检索到的这些帖子也包含在帖子正文模板组件中。这是帖子正文模板,并且在其中添加了注释组件。我也不知道这是否是最好的做法

import React, { Component } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FavoriteIcon from '@material-ui/icons/Favorite';
import EcoIcon from '@material-ui/icons/Eco';
import IconButton from '@material-ui/core/IconButton';
import Grid from '@material-ui/core/Grid';
import Comment from './comments';



const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
  },
}));

const fr = {
  float: 'right'
}

const giphyRes = {
    width: '300px',
    height: '300px'
}



     export default function PostBodyTemplate(props) {

         const classes = useStyles();
        //  render() {
             return (
                <Grid item xs={12} xl={8} lg={8} style={fr}>
                <Card className={classes.card}>
                <CardContent>
                <Paper className={classes.root}>
                <Typography variant="h5" component="h2" style={fr}>
                      {props.userWhoPosted} Gave A VH5 To Julio
                  </Typography>
                    <Typography variant="h5" component="h3">
                      {props.title}
                    </Typography>
                    <Typography component="p">
                      {props.postBody}
                    </Typography>
                    <img src={props.giphyUrl} style={giphyRes}/>
                </Paper>
                </CardContent>
                <CardActions>
                <IconButton aria-label="add to favorites">
                    <FavoriteIcon />
                    <div>Add Gif</div>
                  </IconButton>
                  <IconButton aria-label="share">
                    <EcoIcon />
                    <div>Add Photo</div>
                  </IconButton>
                <TextField
                  id="standard-full-width"
                  label="Reply"
                  style={{ margin: 8 }}
                  placeholder="Reply to Author"
                  fullWidth
                  margin="normal"
                  InputLabelProps={{
                    shrink: true,
                  }}
                />
                  <Button size="small">Submit</Button>
                </CardActions>

                <Comment {**THIS IS WHERE I WANT THE COMMENTS TO GO IF POST HAS COMMENTS**} />

              </Card>
              </Grid>
             )
        //  }
     }
import React,{Component}来自“React”
从'@material ui/core/styles'导入{makeStyles};
从“@material ui/core/Paper”导入纸张;
从“@material ui/core/Typography”导入排版;
从“@material ui/core/Card”导入卡片;
从“@material ui/core/CardActions”导入CardActions;
从“@material ui/core/CardContent”导入CardContent;
从“@material ui/core/Button”导入按钮;
从“@material ui/core/TextField”导入TextField;
从“@material ui/icons/Favorite”导入收藏夹图标;
从“@material ui/icons/Eco”导入EcoIcon;
从“@material ui/core/IconButton”导入IconButton;
从“@material ui/core/Grid”导入网格;
从“/comments”导入注释;
const useStyles=makeStyles(主题=>({
根目录:{
填充:主题。间距(3,2),
},
}));
常数fr={
浮动:“对”
}
常数giphyRes={
宽度:“300px”,
高度:“300px”
}
导出默认函数PostBodyTemplate(道具){
const classes=useStyles();
//render(){
返回(
{props.userwhoposter}给了胡里奥一个VH5
{props.title}
{props.postBody}
添加Gif
添加照片
提交
)
//  }
}
我想完成的是这种性质的事情,但我遇到了困难:

const postItems = reversedProps.map(post => (

  <PostBodyTemplate key={post.id} title={post.title} postBody={post.postBody} giphyUrl = 

{post.giphyUrl} userWhoPosted={post.userIdName}/>

 **If the result of PostIds.Map(getComments) returns a post ID that equals the same Post Id as 
 above, send that information to the comments component and have it populate the comments for this 
 post specifically ** So after it populates the post body i want it to basically map through 
  reversedProps.map(getComments) after and display the comments by passing 


  ));
constpositems=reversedProps.map(post=>(
**如果PostIds.Map(getComments)的结果返回的帖子ID与
在上面,将该信息发送到comments组件,并让它填充此组件的注释
post特别**所以在它填充了post主体之后,我希望它基本上可以映射通过
reversedProps.map(getComments)之后,并通过传递来显示注释
));
下面是注释组件(如果有帮助的话)

import React, { useState, useEffect } from "react";
import PropTypes from 'prop-types'
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/postActions';
import { fetchComments } from '../actions/commentActions';
import axios from 'axios';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';



const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
  },
}));

const fr = {
  float: 'right'
}

const giphyRes = {
    width: '300px',
    height: '300px'
}


export default function Comment() {

  const classes = useStyles();


  return (
    <div>                 
          <Paper className={classes.root} value={comment.postId}>
            <Typography variant="h5" component="h3">
            {comment.commentBody}
            </Typography>
            <Typography component="p">
              {comment.userIdName} replied to the post. 
            </Typography>
        </Paper>
    </div>
  );
}


// export default Comment;
import React,{useState,useffect}来自“React”;
从“道具类型”导入道具类型
从'react redux'导入{connect};
从“../actions/postActions”导入{fetchPosts};
从“../actions/commentActions”导入{fetchComments};
从“axios”导入axios;
从“@material ui/core/Paper”导入纸张;
从“@material ui/core/Typography”导入排版;
从'@material ui/core/styles'导入{makeStyles};
const useStyles=makeStyles(主题=>({
根目录:{
填充:主题。间距(3,2),
},
}));
常数fr={
浮动:“对”
}
常数giphyRes={
宽度:“300px”,
高度:“300px”
}
导出默认函数注释(){
const classes=useStyles();
返回(
{comment.commentBody}
{comment.userIdName}回复了帖子。
);
}
//导出默认注释;

这篇文章有很多要通读的地方,因此我非常欣赏advanced。

简短的回答是,要在react中有条件地呈现数据,最好使用:



在上面的代码中,如果post可用,则会以其他方式打印yes(是)。REST调用在React/Redux中是异步的,因此您应该始终将结果存储在Redux中,以保持UI响应。您需要决定何时触发对评论的调用:可以在收到帖子时执行,也可以在您确定将显示帖子时执行,但无论哪种情况,您都希望将结果放入Redux。您可以创建一个对象,其中posted是键,comments数组是值。然后,通过将Redux状态映射到React props来呈现来自Redux的注释,并将数组(如果有的话)传递给comments组件。当注释到达时,状态的更改将触发重新呈现并填充它们


您将希望避免直接从呈现代码触发Comments调用,因为这可能(可能)最终会发送重复调用,因为状态的任何更改都可能导致重新呈现。当您发送调用以加载帖子时,在redux状态中添加“PostsLoading”=true和PostsLoaded=false标志。在减速器中,将PostsLoading设置为false,并将PostsLoaded设置为true。您可以在componentWillReceiveProps方法中检查这些标记,并使用这些标记中的更改来决定何时调用评论服务。

如果我理解正确,您可以从REST服务获取帖子并将其存储在Redux中,然后在呈现帖子时使用另一个REST调用来获取每个帖子的评论。这是正确的吗?是的,帖子是从发送到redux状态的我的帖子Api调用的,评论是从comments Api提取的,只是gett
import React, { useState, useEffect } from "react";
import PropTypes from 'prop-types'
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/postActions';
import { fetchComments } from '../actions/commentActions';
import axios from 'axios';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';



const useStyles = makeStyles(theme => ({
  root: {
    padding: theme.spacing(3, 2),
  },
}));

const fr = {
  float: 'right'
}

const giphyRes = {
    width: '300px',
    height: '300px'
}


export default function Comment() {

  const classes = useStyles();


  return (
    <div>                 
          <Paper className={classes.root} value={comment.postId}>
            <Typography variant="h5" component="h3">
            {comment.commentBody}
            </Typography>
            <Typography component="p">
              {comment.userIdName} replied to the post. 
            </Typography>
        </Paper>
    </div>
  );
}


// export default Comment;
<YourComponent <h1>{isPostAvailable ? 'yes' : 'no'}</h1> />