Javascript 如何根据道具的价值渲染组件?

Javascript 如何根据道具的价值渲染组件?,javascript,reactjs,Javascript,Reactjs,我有一个父组件Dashboard.js。这里我有三个state值,即昨天、上周、上月,我将这个值传递给我的子组件。现在,我想根据我的子组件呈现我的数据。问题是我使用的是componentDidMount()lifecycle方法,它只呈现子组件一次。如何基于传递给子组件的道具呈现数据?父组件是一个react钩子,而名为DataFetchDetails的子组件是一个基于类的组件。附上各自的代码 父组件:-Dashboard.js import React from 'react'; import

我有一个父组件
Dashboard.js
。这里我有三个
state
值,即昨天、上周、上月,我将这个值传递给我的子组件。现在,我想根据我的子组件呈现我的数据。问题是我使用的是
componentDidMount()
lifecycle方法,它只呈现子组件一次。如何基于传递给子组件的道具呈现数据?父组件是一个react钩子,而名为
DataFetchDetails
的子组件是一个基于类的组件。附上各自的代码

父组件:-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;

从“React”导入React;
从'@material ui/styles'导入{makeStyles};
从“@material ui/core”导入{Tabs,Tab,Grid};
从“@material ui/core/AppBar”导入AppBar;
从“@material ui/core/Typography”导入排版;
从“@material ui/core/Box”导入框;
从“道具类型”导入道具类型;
从“@material ui/core/InputLabel”导入InputLabel;
从“@material ui/core/MenuItem”导入菜单项;
从“@material ui/core/FormControl”导入FormControl;
从“@material ui/core/Select”导入选择
进口{
总用户,
LoggedInUsers,
时间选择器,
未注册者
}来自“./组件”;
从“./components/DataFetchDetails”导入DataFetchDetails;
const useStyles=makeStyles(主题=>({
根目录:{
填充顶:主题。间距(4),
填充:主题。间距(4)
},
表单控制:{
边距:主题。间距(1),
最小宽度:120,
},
选择空:{
marginTop:主题。间距(2),
},
}));
功能选项卡面板(道具){
const{children,value,index,…other}=props;
返回(
{儿童}
);
}
功能a11yProps(索引){
返回{
id:`simple tab-${index}`,
“aria控件”:“简单选项卡面板-${index}”,
};
}
常量仪表板=()=>{
const classes=useStyles();
const[value,setValue]=React.useState(0);
常量handleChange=(事件,newValue)=>{
设置值(新值);
};
const[period,setPeriod]=React.useState(“昨天”);
const handleChange1=事件=>{
设置周期(event.target.value);
};
返回(
前一天
上周
上个月
);
};
导出默认仪表板;
子组件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>
        );
      } 
  }
  }

从“React”导入React;
导入{
卡片
万向节,
按钮
分隔器,
卡片内容,
TextField,
卡片行动,
FormControl,
输入标签,
选择,
梅努伊特姆
}来自“@material ui/core”;
从“@material ui/core/Paper”导入纸张;
从“@material ui/core/Table”导入表格;
从“@material ui/core/TableBody”导入表体;
从“@material ui/core/TableCell”导入TableCell;
从“@material ui/core/TableHead”导入表头;
从“@material ui/core/TableRow”导入TableRow;
从“axios”导入axios;
导入'izitoast/dist/css/izitoast.min.css';//加载css
从“iziToast/dist/js/iziToast.min.js”导入iziToast;//您现在可以访问iziToast了
导入'izitoast/dist/css/izitoast.min.css';
const url='MY_ENDPOINT_url';
导出默认类DataFetchDetails扩展React.Component{
建造师(道具){
超级(道具);
此.state={
项目:[],
isLoaded:是的,
renderJsx:false,
}
}
componentDidMount(){
this.setState({period:this.props.period});
常数周期状态={
句号:this.props.period
};
{console.log(“Props period=,this.Props.period)}
axios.post(url、状态)
.然后((响应)=>{
this.setState({period:this.props.period})
this.setState({items:[response.data]});
.catch((错误)=>{
控制台日志(“错误”);
});      
}
render(){
让{isLoaded,items,renderJsx}=this.state;
如果(!已加载){
回装
}
否则{
返回(
成功
失败
进展中
{items.map(item=>(
{item.success}
{item.failure}
{item.inProgress}
))}
{console.log(“Props period render=,this.Props.period)}
);
} 
}
}

后端和api工作正常。我想根据句点的值重新呈现我的子组件。如何解决此问题?

使用
组件将在子组件中接收道具

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

我希望这会有所帮助。

您可以比较道具,即prevProps和当前道具(this.props)对象

组件更新

基于道具重新渲染子组件的生命周期方法

因为组件将接收道具现在已弃用


查看react lifecycle文档或。

您是否在父组件中获得周期值?但一旦调用渲染函数,就会触发componentDidUpdate。因此,如果componentDidUpdate中的状态发生任何更改,整个生命周期将再次调用。ComyoponentDidUpdate仅在第一次渲染后触发。因此,在有限公司