Передача props в reactjs Material ui modal - PullRequest
0 голосов
/ 14 июля 2020

Я новичок в реакции. В этом файле store. js я создал модальное окно, и в этот модальный тег я включил компонент farmerreview для загрузки при открытии модального окна. Мне нужно передать опору uid компоненту farmerreview.

это магазин. 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} /> в модальный файл в магазине. js файл, а в компоненте Farmerreview у меня консоль вошла в функцию useEffect (), но он выводит ноль.

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

Итак, как мне передать реквизиты в модальное окно в reactjs.

Ответы [ 2 ]

1 голос
/ 14 июля 2020

this.farmerid = { uid: null } в Store. Он никогда не обновлялся. Таким образом, при передаче в качестве опоры в <FarmerReview uid={this.farmerid.uid} /> он всегда и навсегда будет null.

Store

Похоже, вы намеревались обновить some farmerid value in state в паре обработчиков.

Переместите объект 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

Хук реакции с пустым массивом зависимостей вызовет обратный вызов только один раз при монтировании компонента. Если вы хотите регистрировать обновление uid, добавьте его в массив зависимостей эффекта.

useEffect(() => {
    console.log(props.uid)
}, [props.uid]);
1 голос
/ 14 июля 2020

Следующий код будет запускаться только один раз при визуализации вашего компонента Store.

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

Итак, в то время ваш uid будет равен нулю. Если вы хотите проверить, правильно ли вы передаете uid, то вы можете console.log следующим образом.

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

Таким образом, useEffect будет срабатывать при любом изменении. Если вы хотите отслеживать изменения uid, вы можете сделать что-то вроде:

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

Important! Вы также должны переместить свой uid внутри своего состояния.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...