javascript - 从下拉列表中选择特定国家/地区时,如何在屏幕上显示来自 data.json 文件的所选国家/地区详细信息
问题描述
数据.json
{
"countries": [
{
"name": "Australia",
"continent": "Oceania",
"rank": 4,
"id": 1
},
{
"name": "England",
"continent": "Europe",
"rank": 5,
"id": 2
},
{
"name": "Namibia",
"continent": "Africa",
"rank": 8,
"id": 3
}
]
}
CountryUI.js
import React from "react";
import { useState, useEffect } from "react";
import { connect } from "react-redux";
import { countryList } from "../actions";
const CountryUi = (props) => {
useEffect(() => {
props.countryList();
}, []);
const [country, setCountry] = useState("");
const [selectedCountry, setSelectedCountry] = useState("id");
const selectHandleChange = (e) => {
setCountry(e.target.value);
props.countries.map((countryObject) => {
console.log(countryObject);
if (countryObject.id === country) {
console.log(countryObject, "result");
setSelectedCountry(countryObject);
return countryObject;
}
});
};
return (
<div>
<h4>Select Country from below dropdown and get the details</h4>
<form className="dropdown-form">
<label className="form-labels">Select Country:</label>
<select className="select-opt" onChange={selectHandleChange}>
{props.countries.map((country) => {
return <option value={country.id}> {country.name} </option>;
})}
</select>
</form>
<div className="form-labels">Selected:{country}</div>
</div>
);
};
const mapStateToProps = (state) => {
return { countries: Object.values(state.countries) };
};
export default connect(mapStateToProps, { countryList })(CountryUi);
api/countries.js
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8080",
});
动作创建者
import countries from "../apis/countries";
import { FETCH_COUNTRYLIST } from "./types";
export const countryList = () => async (dispatch) => {
const response = await countries.get("/countries");
dispatch({ type: FETCH_COUNTRYLIST, payload: response.data });
};
解决方案
您可以使用Array.prototype.find
查找匹配的国家/地区:
const selectHandleChange = ({ target: { value }}) => {
// this will be updated in the next render
setCountry(value)
// so you should use value here
setSelectedCountry(props.countries.find(country => country.id === value))
};
并将 value prop ( country
) 传递给 select 元素
<select className="select-opt" value={country} onChange={selectHandleChange}>
{props.countries.map((country) => {-
// pass a unique key
return <option value={country.id} key={country.id}>{country.name}</option>;
})}
</select>
在 JSX 中,你应该渲染selectedCountry
<div className="form-labels">Selected:{JSON.stringify(selectedCountry)}</div>
推荐阅读
- c# - 如何将 indexOf 用于带有“\”的字符串?
- mongodb - findAndModify 在 shell 上工作,但不在我的应用程序中
- aurelia - 更改现有项目的顺序时,SortValueConverter 无法正常工作
- reactjs - 你如何为 React 配置 VSCode jsconfig?
- algorithm - 在计数排序中为什么我们必须存储计数数组元素的累积和
- jasmine - 如何处理量角器中的弹出窗口
- linker - 我有 node-gyp 交叉编译的链接器问题
- python - Selenium 在 PC 和 RPI 上的性能差异
- r - 使用 apply 在 R 中的多个列上运行函数
- pandas - pd.concat() 和 pd.merge() 之间的区别以及为什么我会得到错误的输出?