javascript - 如何使用 React 下拉列表中的选定值作为 api url id?
问题描述
我想在用户选择所需的值后使用 id 将 url 中的特定数据呈现到表中,所以这是我的代码:为选择选项获取数据:
export default function Dashboard() {
const [value, setValue] = useState();
const [students, setstudents] = useState([]);
useEffect(() => {
const fetchStudents = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users",
headers: {
"Content-Type": "application/json",
},
});
setstudents(resp.data);
} catch (err) {}
};
fetchStudents();
}, []);
const classes = useStyles();
const [selected,setselected]=useState();
const options = students.map(s => ({
"value" : s.id,
"label" : s.username
}))
const handleChange = (event) => {
setselected(event.value);
};
现在在仪表板功能中获取选定值的数据:
const [tabl, settabl] = useState([]);
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: "https://jsonplaceholder.typicode.com/users"+{selected},
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
fetchtabl();
}, []);
const getTableData = (tabl) => {
return tabl.map((tab) => [
tab.id,
tab.name,
tab.username,
]);
};
现在渲染数据作为回报:
Select the course:
<Select options={options} onChange={handleChange}/>
<Table
tableHead={["Course Code", "Course Name", "Survey Link"]}
tableData={getTableData(tabl)}
tableHeaderColor="primary"
/>
但是在选择所需的值后什么都没有出现我该如何修复它并且反应是否允许使用这样的选定值?
数据
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
解决方案
因此,根据评论部分中的对话,该值存在于selected
. 那么唯一的问题是useEffect
不会因为空的依赖数组而触发更改。
我建议对您的代码进行一些修改:
- 添加到依赖数组
selected
,因为[selected]
一旦你改变了那个状态,它就会触发函数。 - 检查
null
orundefined
值,以免在没有值的情况下连接。 - 我还在你的 URL 中添加了一个额外的斜杠,
users
所以现在它是users/
. - 所以 URL 将在一天结束时:
`https://jsonplaceholder.typicode.com/users/${selected}`
根据解释尝试:
useEffect(() => {
const fetchtabl = async () => {
try {
const resp = await Axios({
method: "GET",
url: `https://jsonplaceholder.typicode.com/users/${selected}`,
headers: {
"Content-Type": "application/json",
},
});
settabl(resp.data.surveys);
} catch (err) {
console.log(err);
}
};
if (selected) {
fetchtabl();
}
}, [selected]);
+1 建议:
也许它不相关,但您有一个可能不需要.map()
的额外内容,因此请尝试:[]
const getTableData = (tabl) => {
return tabl.map((tab) => ({
tab.id,
tab.name,
tab.username,
}));
};
这样将返回一个具有, ,.map()
属性的对象数组。id
name
username
推荐阅读
- laravel - 为 Laravel Nova 启用 VueJS 开发工具
- c# - 尽管使用了 broadFileSystemAccess,但访问被拒绝
- rabbitmq - 在 AMQP 0.9 (rabbitmq) 中 app_id 和 cluster_id 字段是什么
- python - Python:while循环中“else”的目的
- gmail-addons - Gmail 插件 - 在多个线程中使用 getMessages() 时“缺少访问令牌”(但对于当前消息的线程来说很好)
- azure - 如何使用 MongoDB API 将 Azure Databricks 连接到 Cosmos DB?
- c# - ASP.NET核心webapi中的Tryvalidatemodel在单元测试中抛出空引用异常
- ios - 如何在 Swift 中使用 Alamofire 时将 JSON 响应存储到缓存中
- unix - shell中的命令在“-”之后获取第二个数值
- web2py - 301将带有斜杠的网址重定向到不带斜杠的网址web2py