【问题标题】:How to set the first value in a select dropdown to as a default react如何将选择下拉列表中的第一个值设置为默认反应
【发布时间】:2020-08-17 22:51:06
【问题描述】:

我有一个反应程序,它根据下拉列表的值显示一个表格。我希望程序默认根据下拉列表中的第一个值显示表格。

下拉列表中的第一个值与默认值有很大不同,并且下拉列表值总是在变化。因此,数据在首次加载时可能会产生误导。

这是我的代码的 sn-p,里面有一点描述。谢谢。

const CompletenessApp = () => {
    const [completeness, setcompleteness] = useState([]);
    const [loading, setloading] = useState(false);
    const [valueSelected, setValueSelected] = useState({value:'all'});
    const [periodSelected, setPeriodSelected] = useState({value:'20200702'}); // the default value that is used to filter the data.
    const valid = [
        {id:"all", variable:"all"},{id:"true", variable:"true"}, {id:"false", variable:"false"}, {id:"null", variable:"null"},
    ];
    useEffect(() => {
        const fetchData = async () => {
            try{
                const res = await axios.get('http://localhost:8000/api/completeness/');
                setcompleteness(res.data);
                setloading(true);
            } catch (e) {
                console.log(e)
            }
        }
        fetchData();
    }, []);
    // when the page loads for the first time it filters the data based on the period value set in the state. I want the data to be filtered based on the first value in the dropdown instead, the first value in the dropdown is different from the default value set.
    const handlePeriodChange = e => {
        setPeriodSelected({value : e.target.value})
    }

    const handleValueChange = e => {
        let boolvalue = Boolean
        e.target.value === 'true'? boolvalue = true:
        e.target.value === 'false'? boolvalue = false:
        e.target.value === 'all'? boolvalue = 'all':
        boolvalue=null
        setValueSelected({value : boolvalue})
    }
    //filtered data to be displayed
    const filteredCompleteness = completeness.filter(
        completedata=> (completedata.period === periodSelected.value)
        &&(valueSelected.value !== 'all'?completedata.complete === valueSelected.value:{}))


    return(
        <div>
            <div className="selection-row">
                <div className="stats-columns">
                    <div className="stats-label">Period</div>
                    //the relevant dropdown is here
                    <select onChange={e => handlePeriodChange(e)}>
                        {Array.from(new Set(completeness.map(obj => obj.period)))
                            .sort().reverse()
                            .map(period => {
                            return <option value={period}>{period}</option>
                        })}
                    </select>
                </div>
                <div className="stats-columns">
                    <div className="stats-label">Value</div>
                    <select onChange={e => handleValueChange(e)}>
                        {valid.map((obj) => {
                            return <option value={obj.id}>{obj.variable}</option>
                        })
                        }
                    </select>
                </div>
            </div>
            <hr></hr>
            <div className="results-table">
                 //table is displayed here
            </div>
        </div>
    );
}


export default CompletenessApp;

【问题讨论】:

    标签: reactjs


    【解决方案1】:
    // above return
    const options = Array.from(new Set(completeness.map((obj) => obj.period)))
      .sort()
      .reverse()
      .map((period) => {
        return {
          value: period,
          label: period,
        };
      });
    
    
    // in jsx
    
    <select defaultValue={options[0].value} onChange={e => handlePeriodChange(e)}>
     {
      options.map((obj) => {
        return <option value={obj.value}>{obj.label}</option>;
      })
    }
    </select>
    

    试试这个并告诉我。

    【讨论】:

    • 我试过了。我做到了,但似乎 options[0].value 正在返回“未定义值”错误。但它在控制台上显示得很好。
    • 是的,当 options 是一个空白数组时,可能会发生这种情况。当完整性变量本身是空白数组时,可能会发生这种情况。然后你应该检查然后设置默认值
    • 是的,我意识到在填充它之前首先返回一个空的完整性数组。谢谢让我试着解决这个问题。
    猜你喜欢
    • 2014-07-07
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多