繁体   English   中英

如何根据反应选择中的选定值有条件地呈现数据

[英]How to conditionally render data based on selected value in react-select

嘿,我是新来的反应和自学。 有人可以指出我正确的方向或给我一些线索。 我的页面顶部显示了一个反应选择组件。 此组件中的数据是从我的 useContext 提供程序填充的。 我想要的结果是,当用户选择某个组件时,我想用具有相应数据的相关卡片填充页面。 所有数据都在我的 authContext 中可用。

我已经走到了这一步,但是当用户从下拉列表中选择值时,没有任何填充。 有人可以帮忙吗:-

import React, { useContext, useEffect, useState } from 'react'
import styles from './FullRecord.module.css'
import {AuthContext} from '../../shared/context/auth-context'
import Select from 'react-select'
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';


const useStyles = makeStyles({
    custom: {
      backgroundColor: "#558d6b",
      fontWeight: "bold"
    },
    customFont: {
      fontWeight: "bold",
      fontSize: "20px"
    },
    customFont1: {
      fontWeight: "light"
    }
  });

  

const FullRecord = (props) => {

    let data

    const auth = useContext(AuthContext)

    const [edition1, setEdition1] = useState(false)

    const options = auth.tournaments.map((tournament) => {
        return {
            value: tournament.TournamentName,
            label: tournament.TournamentName,
        }
        })

    console.log(options)

    const classes = useStyles();
        
    const handleChange = (selectedValue1) => {
        console.log(selectedValue1)
        setEdition1(true)
        const {value}  = selectedValue1
        console.log(value)
        console.log(edition1)
        if(value === 'GSM Edition 1'){
            const noOfMatches = auth.profile.MemberMatches.filter((match) => match.TournamentName === 'GSM Edition 1')
            console.log(noOfMatches)
                data = 
                    <div>
                 <li className={styles['member-item']}>
                     <Card className={classes.custom} variant="outlined">
                          <CardContent>
                               <Typography className={classes.customFont}  gutterBottom>
                                     Number Of Matches Played
                                </Typography>
                                <Typography className={classes.customFont}>
                                     {noOfMatches}
                                </Typography>
                           </CardContent>
                      </Card>
                 </li>               
            </div>
            }    
        }

      


    return (
        <React.Fragment>
            <div className={styles['fullrecord__maindiv']}>
                <Select 
                //  value={options.value}
                 onChange={handleChange}
                 options={options}
                />
            </div>
            {edition1 && <div>
                {data}
            </div>}
        </React.Fragment>
    )
}

export default FullRecord

在此处输入图片说明

在此处输入图片说明

    You can Use This for React Select:
    
    Example of Data in DropDown::
    const projectTermData = [];
    const terms = [{"id":"1","description":"Due on receipt","value":"0"},{"id":"2","description":"Net 30","value":"30"},{"id":"3","description":"Net 60","value":"60"},{"id":"4","description":"Net 90","value":"90"}]
        terms.map(el => {
          projectTermData.push({
              key: el.id,
              value: el.id,
              label: el.description
          });
        });
        <Select name="term_id" style="" isMulti={false} defaultValue={ term_id != "" ? projectTermData.find( item => item.value === term_id ) : { label: "Select Customer Type", value: 0 } } onChange={projectTermData => handleChange({ name: "term_id", key: projectTermData.value, label: projectTermData.label, value: projectTermData.value }) } options={projectTermData} />
    
    <!-- end snippet -->

<!-- Handle Change Function -->

 const handleChange = (e)=> {
        let obj;
        if (e.target) {
            obj = e.target;
        } else {
            obj = e;
        }
        const { name, key, label, value } = obj;
        setFormValues(prev => ({
            ...prev,
            [name]: obj.value
        }));
        // setFormErrors({...errorValues})
        let errorVar = fieldErrorMap[name];
        let errorVarMsg = fieldErrorMsgMap[name];
        if (obj.value === "") {
            setFormErrors({ ...formErrors, [errorVar]: true });
        } else {
            if (new Date(formValues.start_date) >= new Date(formValues.end_date)) {
                setFormErrors({ ...formErrors, endDtErrorMsg: true });
            } 
            setFormErrors({ ...formErrors, [errorVar]: false });
        }
    };

data似乎是来自选择选项的“派生状态”,但由于它不在状态,因此您没有任何东西可以触发重新渲染来执行任何操作。

我建议将选定的选项存储在 state 中并计算data JSX。

const FullRecord = (props) => {
  const auth = useContext(AuthContext);

  const [edition1, setEdition1] = useState(false);
  const [selectedOption, setSelectedOption] = useState({}); // <-- add selected option state

  const options = auth.tournaments.map((tournament) => ({
    value: tournament.TournamentName,
    label: tournament.TournamentName,
  }))

  const classes = useStyles();
      
  const handleChange = (selectedValue1) => {
    setEdition1(true);
    setSelectedOption(selectedValue1); // <-- update selected option state
  }

  return (
    <React.Fragment>
      <div className={styles['fullrecord__maindiv']}>
        <Select 
          onChange={handleChange}
          options={options}
        />
      </div>
      {edition1 && selectedOption.value === 'GSM Edition 1' (
        <div>
          <li className={styles['member-item']}>
            <Card className={classes.custom} variant="outlined">
              <CardContent>
                <Typography className={classes.customFont}  gutterBottom>
                  Number Of Matches Played
                </Typography>
                <Typography className={classes.customFont}>
                  {auth.profile.MemberMatches.filter((match) => match.TournamentName === 'GSM Edition 1')}
                </Typography>
              </CardContent>
            </Card>
          </li>
        </div>
      )}
    </React.Fragment>
  );
}

暂无
暂无

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

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