将道具传递给reactjs材质用户界面模式

时间:2020-07-14 05:49:24

标签: reactjs material-ui react-props

我是新来的人。在这个store.js文件中,我创建了一个模态,并且在此模态标签中,我包括了farmerreview组件以在打开模态时加载。我需要将uid属性传递给farmerreview组件。

这是store.js文件,我在该文件中包含了模式代码。

import React, { Component, useState } from 'react';
import styles from './store.module.css';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import Grid from '@material-ui/core/Grid';
import Modal from '@material-ui/core/Modal';
import Paper from '@material-ui/core/Paper';
import { Button } from '@material-ui/core';
import instance from '../../stocks-list';
import FarmerReview from '../reviewModule/farmerReview';

class Store extends Component {

  state = {
    vege: '',

    veges: [],
    eco: '',
    open: false,
  }

  farmerid = {
    uid: null
  }

  handleOpen = () => {
    this.setState({
      ...this.state, open: true
    })
  };

  handleClose = () => {
    this.setState({
      ...this.state, open: false
    })
  };


  handleChange(event) {
    this.setState({
      vege: event.target.value
    })
    console.log(this.state.vege)
  }

  handleChangeeco(event) {
    this.setState({
      eco: event.target.value
    })
    console.log(this.state.vege)
  }

  handlenav(vege1, size1, img1, seller1, eco_centre1, FarmerId, Farmer,) {

    this.props.history.push({
      pathname: '/checkout',
      state: {
        vege: vege1,
        size: size1,
        img: img1,
        eco_centre: eco_centre1,
        Farmer: seller1,
        FarmerId: FarmerId

      }

    })
  }

  goToFarmerReview(e) {
    console.log(e)

    this.setState({
      ...this.farmerid, uid: e
    })
    console.log(this.farmerid.uid)
    this.handleOpen();
  }

  componentDidMount() {


    instance.get('/Stocks.json')



      .then(response => {
        for (let key in response.data) {
          console.log(response.data[key])

          const tempStock = [];
          for (let key in response.data) {
            tempStock.unshift(
              {
                ...response.data[key]
              }
            )
          }
          this.setState({ veges: tempStock })
        }

      })

    console.log(this.state)

  }

  reset() {
    this.setState({
      vege: '',
      eco: ''
    })
  }

  render() {
    return (
      <div className={styles.main}>
        <h1>KRUSHIGANUDENU STORE</h1>
        <Modal style={{
          top: '20%',
          left: '30%',
          right: '30%',
          bottom: '20%',

        }}
          open={this.state.open}
          onClose={this.handleClose}
          aria-labelledby="simple-modal-title"
          aria-describedby="simple-modal-description"
        >

          <FarmerReview uid={this.farmerid.uid} />
        </Modal>

        <div className={styles.filters}>
          <InputLabel className={styles.label} id="demo-simple-select-label">Vegetable</InputLabel>
          <Select
            className={styles.select}
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={this.state.vege}
            onChange={this.handleChange.bind(this)}
          >

            <MenuItem value={'no filter'}>No filter (සියල්ල)</MenuItem>
            <MenuItem value={'Potato (අල)'}>Potato (අල)</MenuItem>
            <MenuItem value={'Beet (බීට්)'}>Beet (බීට්)</MenuItem>
            <MenuItem value={'Carrot (කැරට්)'}>Carrot (කැරට්)</MenuItem>
            <MenuItem value={'Pumpkin (වට්ටක්කා)'}>Pumpkin (වට්ටක්කා)</MenuItem>
            <MenuItem value={'Cabbage (ගෝවා)'}>Cabbage (ගෝවා)</MenuItem>
            <MenuItem value={'Brinjal (වම්බටු)'}>Brinjal (වම්බටු)</MenuItem>
            <MenuItem value={'Beans (බෝංචි)'}>Beans (බෝංචි)</MenuItem>
            <MenuItem value={'Tomato (තක්කාලි)'}>Tomato (තක්කාලි)</MenuItem>
            <MenuItem value={'Chili (මිරිස්)'}>Chili (මිරිස්)</MenuItem>

          </Select>

          <InputLabel className={styles.label} >Eco Centre</InputLabel>
          <Select
            className={styles.select}
            labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={this.state.eco}
            onChange={this.handleChangeeco.bind(this)}
          >
            <MenuItem value={'Meegoda'}>Meegoda</MenuItem>
            <MenuItem value={'Dambulla'}>Dambulla</MenuItem>
          </Select>

          <br />

          <Button style={{ marginTop: 10 }} variant="contained" color="green" onPress={this.reset}>Reset Filters</Button>
        </div>

        <div className={styles.items}>

          <Grid container>
            <Grid item xs={12}>
              <Grid container justify="center" spacing={2}>
                {this.state.veges.map((value) => (
                  <Grid key={value} item>
                    {this.state.vege === 'no filter' || this.state.vege.substring(0, 5) === value.crop.substring(0, 5) || (this.state.vege.substring(0, 5) === value.crop.substring(0, 5) && this.state.eco === value.economicCenter) || this.state.vege === '' ?
                      <Paper style={{
                        height: 530, backgroundColor: 'white',
                        width: 300
                      }} > <img style={{ height: 280, width: 300, objectFit: 'cover' }} src={value.image}></img>
                        <div style={{ padding: 10 }}>
                          <h4>{value.crop}</h4>
                          <h5>{value.quantity}kg</h5>
                          <h5 onClick={() => this.goToFarmerReview(value.uid)}>{value.name}</h5>
                          <h5>{value.economicCenter}</h5>
                          <div style={{ display: 'flex' }}>
                            <Button variant="outlined" color="primary">
                              details
</Button>
                            <Button onClick={() => this.handlenav(value.crop, value.quantity, value.image, value.name, value.economicCenter, value.uid)} variant="outlined" color="secondary">
                              buy
</Button></div>
                        </div>
                      </Paper> : null}
                  </Grid>
                ))}
              </Grid>
            </Grid>
          </Grid>

        </div>
      </div>
    )
  }
}

export default Store;

这是farmerreview.js文件,当我单击模式时,该组件打开。

import React, { useState,useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import './farmerreview.css'
import TextField from '@material-ui/core/TextField';
import Rating from '@material-ui/lab/Rating';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';

const labels = {
    0.5: 'Useless',
    1: 'Useless+',
    1.5: 'Poor',
    2: 'Poor+',
    2.5: 'Ok',
    3: 'Ok+',
    3.5: 'Good',
    4: 'Good+',
    4.5: 'Excellent',
    5: 'Excellent+',
};

const useStyles = makeStyles({
    root: {
        width: 200,
        display: 'flex',
        alignItems: 'center',

    },
});



function FarmerReview(props) {
    const [value, setValue] = useState(2);
    const [hover, setHover] = useState(-1);
    const classes = useStyles();
    
    useEffect(() => {
  
        console.log(props.uid)
    }, [])

    return (

        <div className="main">
            <div className="box">
                <Grid container spacing={5}
                    direction="row"
                    justify="center"
                    alignItems="center">
                    <Grid item xs={10} align="left">
                        <h3>Thushara</h3>
                    </Grid>

                    <Grid item xs={10} align="center">
                        <form noValidate autoComplete="off">


                            <Grid item xs={12} align="left">
                                <TextField id="standard-basic" label="Your Review" fullWidth multiline />
                            </Grid>
                            <Grid item xs={12} align="left">
                                <TextField id="standard-basic" label="Your Name" fullWidth />
                            </Grid>
                            <div style={{ marginTop: '20px' }}>
                                <Grid item xs={12} align="center">
                                    <Rating
                                        name="hover-feedback"
                                        value={value}
                                        precision={0.5}
                                        onChange={(event, newValue) => {
                                            setValue(newValue);
                                        }}
                                        onChangeActive={(event, newHover) => {
                                            setHover(newHover);
                                        }}
                                    />
                                    {value !== null && <Box ml={2}>{labels[hover !== -1 ? hover : value]}</Box>}
                                </Grid>
                                <div style={{ marginTop: '20px' }}>
                                    <Grid item xs={12} align="center">
                                        <Button variant="contained" color="primary">
                                            Submit Review
                                    </Button>
                                    </Grid>
                                </div>
                                <div style={{ marginTop: '20px' }}>
                                    <Grid item xs={12} align="center">
                                        <Card variant="outlined">
                                            <CardContent>

                                                <Rating
                                                    name="hover-feedback"
                                                    value={value}
                                                    precision={0.5}
                                                    
                                                />
                                                
                                                <Typography color="textSecondary">
                                                    adjective
                                                </Typography>
                                                <Typography variant="body2" component="p">
                                                    well meaning and kindly.
                                                <br />
                                                    {'"a benevolent smile"'}
                                                </Typography>
                                            </CardContent>
                                        </Card>
                                    </Grid>
                                    <Grid item xs={12} align="center">
                                        <Card variant="outlined">
                                            <CardContent>

                                                <Rating
                                                    name="hover-feedback"
                                                    value={value}
                                                    precision={0.5}
                                                    onChange={(event, newValue) => {
                                                        setValue(newValue);
                                                    }}
                                                    onChangeActive={(event, newHover) => {
                                                        setHover(newHover);
                                                    }}
                                                />
                                                <Typography color="textSecondary">
                                                    adjective
                                                </Typography>
                                                <Typography variant="body2" component="p">
                                                    well meaning and kindly.
                                                <br />
                                                    {'"a benevolent smile"'}
                                                </Typography>
                                            </CardContent>
                                        </Card>
                                    </Grid>
                                    <Grid item xs={12} align="center">
                                        <Card variant="outlined">
                                            <CardContent>

                                                <Rating
                                                    name="hover-feedback"
                                                    value={value}
                                                    precision={0.5}
                                                    onChange={(event, newValue) => {
                                                        setValue(newValue);
                                                    }}
                                                    onChangeActive={(event, newHover) => {
                                                        setHover(newHover);
                                                    }}
                                                />
                                                <Typography color="textSecondary">
                                                    adjective
                                                </Typography>
                                                <Typography variant="body2" component="p">
                                                    well meaning and kindly.
                                                <br />
                                                    {'"a benevolent smile"'}
                                                </Typography>
                                            </CardContent>
                                        </Card>
                                    </Grid>
                                
                                </div>
                            </div>
                        </form>
                    </Grid>


                </Grid>
            </div>
        </div>

    )
}



export default FarmerReview

我已经将<FarmerReview uid={this.farmerid.uid} />包括在store.js文件中的模式中,并且在Farmerreview组件中,我已经在useEffect()函数中登录了控制台,但是它打印出了null。

useEffect(() => {
        console.log(props.uid)
}, [])

所以我该如何将props传递给reactjs中的模式。

2 个答案:

答案 0 :(得分:1)

以下代码将在呈现商店组件时仅运行一次。

useEffect(() => {
        console.log(props.uid)
}, [])

因此,那时您的uid将为null。如果要检查是否以正确的方式传递了uid,则可以通过以下方式进行console.log。

useEffect(() => {
        console.log(props.uid)
})

这样,useEffect将在任何更改时被触发。如果要跟踪uid的更改,则可以执行以下操作:

useEffect(() => {
        console.log(props.uid)
}, [props.uid])

Important!您还应该在自己的状态内移动uid。

答案 1 :(得分:1)

this.farmerid = { uid: null }中的

Store。它永远不会更新。因此,当作为道具传递给<FarmerReview uid={this.farmerid.uid} />时,它将永远永远是null

商店

您似乎打算在几个处理程序中更新 some farmerid的状态值。

farmerid对象移动到状态对象中。

state = {
  vege: '',
  veges: [],
  eco: '',
  open: false,
  farmerid: {
    uid: null,
  },
}

并将传递给FarmerReview的引用更新为当前状态。

<FarmerReview uid={this.state.farmerid.uid} />

由于this.farmerid不再存在,所以不要忘记通过正确地传播farmerid对象来修复处理程序。

goToFarmerReview(e) {
  console.log(e);
  this.setState({
    farmerid: {
      ...this.state.farmerid,
      uid: e,
    },
  });
  this.handleOpen();
}

FarmerReview

具有空依赖项数组的react钩子仅在组件装入时才触发一次回调。如果您想在uid更新时记录日志,请将其添加到效果的依赖项数组中。

useEffect(() => {
    console.log(props.uid)
}, [props.uid]);