reactjs - 当 Url Typed 我需要在调用 api 时获取 react js 中的单个数据
问题描述
当我输入此http://localhost:3000/hell/:2
页面时,页面会加载但不会获取 id 为 2 的单个项目
但是当我单击按钮时,页面会显示 ID 为 2 的单个项目,当我输入http://localhost:3000/hell/:2
为 URL时,我需要显示数据
""""""""""代码运行,但它以段落格式显示,因此我进行了编辑并使代码更易于理解"""""""""
代码是--->>
在 App.js-->
<div className="App">
<div className='body'>
<Router history={History}>
<Switch>
<Route path="/hell/:id"><Hell/></Route>
</Switch>
</Router>
</div>
</div>
在 Hello.js-->
let {id} = useParams();
let di = id;
const [loading,setloading] = useState([false]);
const [posts,setposts] = useState([]);
const [search,setsearch] = useState("");
const [message,setmessage] = useState("");
const history = useHistory();
useEffect(()=>{
const getload = async ()=>{
setloading(true);
const response = await axios.get(`http://127.0.0.1:8000/list/`);
const message = "Error";
setposts(response.data);
setmessage(message);
setloading(false);
}
},[]);
console.log({di});
function inputhandler(a){
id = a;
history.push(generatePath("/hell/:id", { id }));
setsearch(a);
}
return (
<div>
<h1>Find : {id}</h1>
{
posts.map((curElem) =>{
return(
<div>
<Link key={curElem.id} to={curElem.id} onClick={() => inputhandler(curElem.id)}>{curElem.title}</Link>
</div>
)
})
}
{
loading ?(<h4>Loading...{message}</h4>):(
(posts.filter((value)=>{
if(value.id===(search)){
return message;
}
})
.map(item =><Help key={item.id} title={id}></Help>)))
}
</div>
)
}
解决方案
您已经访问了id
路由匹配参数,但从未使用过它。
您没有正确形成链接目标。正确链接后,无关onClick
处理程序无需使用该值设置任何search
状态,item.id
因为您可以id
从参数中使用链接的权利。
请记住也要调用getload
,以便posts
更新状态。
你好.js
const history = useHistory();
const { id } = useParams(); // <-- current `id` from "/hell/:id"
const [loading,setloading] = useState([false]);
const [posts,setposts] = useState([]);
const [message,setmessage] = useState("");
useEffect(()=>{
const getload = async ()=>{
setloading(true);
const response = await axios.get(`http://127.0.0.1:8000/list/`);
const message = "Error";
setposts(response.data);
setmessage(message);
setloading(false);
}
getload(); // <-- need to call to make the GET request
},[]);
return (
<div>
<h1>Find : {id}</h1>
{posts.map((curElem) => {
return(
<div key={curElem.id}> // <-- React key on outermost element
<Link
// generate target path here
to={generatePath("/hell/:id", { id: curElem.id })}
>
{curElem.title}
</Link>
</div>
)
})}
{loading
? <h4>Loading...{message}</h4>
: posts.filter((value) => value.id === id) // <-- filter by id
.map(item => <Help key={item.id} title={id}></Help>)
}
</div>
)
推荐阅读
- javascript - 在 Blazor 应用程序中恢复身份
- javascript - 属性包含确切的数字选择器,因此找到 3 但不是 13 或 23
- azure - Azure 运行手册 | 在事务性电子邮件中从我的 Azure 存储帐户发送附件
- c++ - 如何用最后一个数字翻转字符串中的第一个数字,然后是倒数第二个和倒数第二个,依此类推?
- javascript - 如何循环指定的代码区域以在 Javascript 中编译数据?
- sql - Woocommerce,使用 SQL 更新 ACF 字段和简短描述
- django - ViewSets 操作的不同排序字段
- single-sign-on - 多个重定向 url 在 slack sso 中不起作用
- sshd - 始终使用默认的 ssh 配置
- vue.js - 将框架加载到多个捆绑包