私有路由和读取Params - React + Django

Private route and reading Params - React + Django

我正在按照他们使用 react-router v5 的教程构建 Django + React 应用程序,我使用 v6.2.1(代码在这里:https://github.com/linkedweb/realest_estate/blob/main/src/containers/ListingDetail.js)。

我想要一个 PrivateRoute 用于经过身份验证的用户呈现产品的详细信息。我试图根据此 post 尤其是 (React - TypeError: Cannot read properties of undefined (reading 'params')) 调整代码,但我无法使其正常工作,我得到:

“未捕获类型错误:无法读取未定义的属性(读取 'params')”

我尝试了很多变体,但这是我认为最接近正确的方法:

App.js

const App = () => (
  <Provider store={store}>
    <Router>
      <Layout >
        <Routes>
          <Route exact path='/' element={<Home />} />
          ...
          <Route exact path='/listings' element={<Listings/>} />
          <Route path='/listings/:id' element={<PrivateRoute />}>
            <Route path='' element= {<ListingDetail />}/>
          </Route> 
          <Route path="*" element={<NotFound />} /> 
        </Routes>
      </Layout>
    </Router>
  </Provider>)

私有路由

const PrivateRoute = ({ auth: {isAuthenticated, loading }, ...rest  }) => {
    return (!isAuthenticated && !loading) ? (<Navigate to='/login' />) : (<Outlet {...rest}/>)}
    
PrivateRoute.propTypes = {
    auth: PropTypes.object.isRequired};

const mapStateToProps = state => ({
    auth: state.auth});

export default connect(mapStateToProps)(PrivateRoute);

房源详情

const ListingDetail = (props) => {
    const [listing, setListing] = useState({});

    useEffect(() => {
        const slug = props.match.params.id;

        const config = {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`}};

        axios.get(`http://localhost:8000/api/listings/${slug}`, config)
        .then(res => {
            setListing(res.data);
        })
        .catch(err => { }); });

    return (
        <div className='listingdetail'>
            <p>{listing.title}</p>
        </div>
    );};

export default ListingDetail;

我试图将 'const slug = props.match.params.id;' 更改为 'const { slug } = useParams();',甚至在 useEffect 之外,但没有成功!

我该怎么做才能检索有关产品的数据并显示它们?

祝你有愉快的一天!

path 属性移动到您要渲染的 Route 中,您希望路由组件访问路由参数 (slug).

<Route element={<PrivateRoute />}>
  <Route
    path='/listings/:slug'
    element= {<ListingDetail />}
  />
</Route>

ListingDetail 应该使用 useParams 钩子来检索 slug 路由参数。访问 slug 路由参数 outside useEffect 钩子并将 slug 添加到 useEffect 钩子的依赖数组。

const ListingDetail = () => {
  const { slug } = usePrams();
  const [listing, setListing] = useState({});

  useEffect(() => {
    const config = {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
    };

    axios.get(`http://localhost:8000/api/listings/${slug}`, config)
      .then(res => {
        setListing(res.data);
      })
      .catch(err => { });
  }, [slug]);

  return (
    <div className='listingdetail'>
      <p>{listing.title}</p>
    </div>
  );
};