首页 > 解决方案 > 当 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>
)
}

标签: reactjsreact-hooksreact-routerreact-router-dom

解决方案


您已经访问了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>
)

推荐阅读