简体   繁体   English

如何根据 props 的值渲染组件?

[英]how to render components based on the value of props?

I have a parent component Dashboard.js .我有一个父组件Dashboard.js Here I have three values of state namely yesterday, lastWeek, lastMonth and I'm passing this value to my child component.在这里,我有state的三个值,即昨天、lastWeek、lastMonth,我将此值传递给我的子组件。 Now I want to render my data depending on my child component.现在我想根据我的子组件来渲染我的数据。 The problem is I'm using componentDidMount() lifecycle method which is rendering the child component only once.问题是我正在使用componentDidMount()生命周期方法,它只渲染一次子组件。 How do I render the data based on the props passed to the child component?如何根据传递给子组件的 props 渲染数据? The parent component is a react hook and the child component called DataFetchDetails is a class based component.父组件是一个反应钩子,名为DataFetchDetails的子组件是一个基于 class 的组件。 Attaching their respective codes附上各自的代码

Parent Component:- Dashboard.js父组件:- Dashboard.js

import React from 'react';
import { makeStyles } from '@material-ui/styles';
import { Tabs, Tab, Grid } from '@material-ui/core';
import AppBar from '@material-ui/core/AppBar';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import PropTypes from 'prop-types';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select'

import {
  TotalUsers,
  LoggedInUsers,
  TimePicker,
  UnregisteredUsers
} from './components';
import DataFetchDetails from './components/DataFetchDetails';

const useStyles = makeStyles(theme => ({
  root: {
    paddingTop: theme.spacing(4),
    padding: theme.spacing(4)
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120,
  },
  selectEmpty: {
    marginTop: theme.spacing(2),
  },
}));

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      <Box p={3}>{children}</Box>
    </Typography>
  );
}

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}


const Dashboard = () => {
  const classes = useStyles();

  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  const [period, setPeriod] = React.useState("yesterday");

  const handleChange1 = event => {
    setPeriod(event.target.value);
  };


  return (

    <div className={classes.root}>
      <Select
        labelId="demo-simple-select-label"
        id="demo-sample-select"
        value={time}
        onChange={handleChange1}
        >

          <MenuItem value={"yesterday"}>Previous day</MenuItem>
          <MenuItem value={"lastWeek"}>Last Week</MenuItem>
          <MenuItem value={"lastMonth"}>Last Month</MenuItem>
        </Select>
      <div className={classes.root}>
        <AppBar position="static">

          <Tabs value={value} onChange={handleChange} aria-label="simple tabs example">
          <Tab label="CONSENT DETAILS" {...a11yProps(0)} />
          <Tab label="ACCOUNT DETAILS" {...a11yProps(1)} />
          <Tab label="DATA FETCH DETAILS" {...a11yProps(2)} />

        </Tabs>
        </AppBar>
        <TabPanel value={value} index={0}>

        </TabPanel>
        <TabPanel value={value} index={1}>

        </TabPanel>
        <TabPanel value={value} index={2}>

        <DataFetchDetails period={period} handlePeriodChange1={handleChange1} />
        </TabPanel>
     </div>

    </div>

  );
};

export default Dashboard;

Child component DataFetchDetails.js:-子组件 DataFetchDetails.js:-

import React from 'react';  
import { 
  Card, 
  CardHeader,
  Button,
  Divider,
  CardContent,
  TextField,
  CardActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem
} from '@material-ui/core';
import Paper from '@material-ui/core/Paper';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import axios from 'axios';
import 'izitoast/dist/css/iziToast.min.css'; // loading css
import iziToast from 'izitoast/dist/js/iziToast.min.js';  // you have access to iziToast now
import 'izitoast/dist/css/iziToast.min.css';

const url = 'MY_ENDPOINT_URL';

export default class DataFetchDetails extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      items : [],
      isLoaded : true,
      renderJsx: false,
    }


}
  componentDidMount() {
    this.setState({period: this.props.period});

    const periodStatus = {
      period : this.props.period      
  };
  {console.log("Props period = ",this.props.period)}

  axios.post(url, periodStatus)
  .then((response) => { 

      this.setState({period : this.props.period}) 
      this.setState({items : [response.data]});


  .catch((error) => {
    console.log("Error");

  });      

  }

  render() {

      let {isLoaded, items, renderJsx } = this.state;

      if(!isLoaded) {
        return <div>Loading</div>
      }

      else {
        return (
          <div>
              <div>
                <Card className="Lock-user"
              >
                <form  > 
                  <CardHeader
                    title=""
                  />
                  <Divider></Divider>
                  <CardContent id="form-input" className=""
                  >

                  </CardContent>
                  <Divider></Divider>
                </form>
              </Card>
              </div>          
          <div>
            <Card>
                <Paper>
                    <Table>         
                  <TableHead>
                  <TableRow>
                      <TableCell> success </TableCell>
                      <TableCell align="right">failure</TableCell>
                      <TableCell align="right">inProgress</TableCell>                   
                  </TableRow>
                  </TableHead>
                  <TableBody>
                      { items.map(item => (
                          <TableRow key={item.success}>
                          <TableCell component="th" scope="row">
                              {item.success}
                          </TableCell>
                          <TableCell align="right">{item.failure}</TableCell>
                          <TableCell align="right">{item.inProgress}</TableCell>                      
                          </TableRow>
                      ))}
                  </TableBody>
                  </Table>
                  {console.log("Props period render = ",this.props.period)}

                  </Paper>
              </Card> 
          </div>
        </div>
        );
      } 
  }
  }

the backend and the api works fine.后端和 api 工作正常。 I want to re render my child component based on the value of the period.我想根据句点的值重新渲染我的子组件。 How do I solve this problem?我该如何解决这个问题?

You you compare the props ie prevProps and current props(this.props) object inside你你比较一下 props 即 prevProps 和 current props(this.props) object 里面

ComponentDidUpdate组件更新

lifecycle method to re-render the child component based on props.生命周期方法,基于 props 重新渲染子组件。

As ComponentWillReceiveProps is deprecated now.由于ComponentWillReceiveProps现在已弃用

https://egghead.io/lessons/react-refactor-componentwillreceiveprops-to-getderivedstatefromprops-in-react-16-3 https://egghead.io/lessons/react-refactor-componentwillreceiveprops-to-getderivedstatefromprops-in-react-16-3

Go through the react lifecycle docs or https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html . Go 通过反应生命周期文档或https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.ZFC35FDC70D5FC69D23EZC88A

Use componentWillRecieveProps in child component.在子组件中使用componentWillRecieveProps

componentWillRecieveProps(props) {
    // props => new props passed
    // this.props => current props
}

I hope that helps.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM