【问题标题】:How to conditionally render data based on selected value in react-select如何根据反应选择中的选定值有条件地呈现数据
【发布时间】:2021-07-18 07:51:00
【问题描述】:

嘿,我是新来的反应和自学成才的人。有人可以指出我正确的方向或给我一些线索。我的页面顶部显示了一个反应选择组件。此组件中的数据是从我的 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

【问题讨论】:

    标签: reactjs react-select


    【解决方案1】:

    似乎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>
      );
    }
    

    【讨论】:

    • 嘿@drewReese 它在编译时给了我这个未定义 selectedValue1 的错误。所以我在函数的开头声明了 let selectedValue1 。不是在运行时它说 Uncaught TypeError: Cannot read property 'value' of undefined。有什么帮助吗?
    • @Sandy 哦,你是对的,selectedValue1.value 在渲染中应该是selectedOption.value,这是添加的新状态。我已经更新了我的答案。对此感到抱歉。
    • 老兄,对不起,它仍然不会......现在它说“TypeError:“GSM Edition 1”不是一个函数”......我在猜测语法......我之前实际上已经尝试过这是同样的错误
    • @Sandy 您在哪里尝试将字符串作为函数调用?这没有任何意义。
    • 我和你一样困惑,但这就是它所说的......显然语法有问题......:(
    【解决方案2】:
        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 });
            }
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多