简体   繁体   English

无法使用路由器和 WordPress API 从列表中渲染出单页数据

[英]Can't render out single page data from list in a react application using router and WordPress API

I'm pretty new to this so apologies in advance if I'm being dumb.我对此很陌生,所以如果我很愚蠢,请提前道歉。 I'm building a react application on top of the WordPress rest API.我正在 WordPress rest API 之上构建一个反应应用程序。 I'm trying to do something pretty basic which is to create a component showing a list of pages, each with a link which takes the user to a new view showing the individual 'page' with all the data for that page.我正在尝试做一些非常基本的事情,即创建一个显示页面列表的组件,每个页面都有一个链接,该链接将用户带到一个新视图,显示单个“页面”以及该页面的所有数据。

I'm almost there but am having problems outputting the correct data on the individual pages.我快到了,但在各个页面上输出正确数据时遇到问题。

The approach I've taken is to take the id from match.params and then match it up with the page id passed down through props using javascript 'find'.我采用的方法是从 match.params 中获取 id,然后使用 javascript 'find' 将其与通过 props 传递的页面 id 匹配。 This kind of works.这种作品。 I can console log the data for the individual page out from inside the 'getPage' method in the PageSingle component if I call it in the render method but the moment I try to access any individual values such as the id I get the old Cannot read property 'id' of undefined.如果我在渲染方法中调用它,我可以从 PageSingle 组件中的“getPage”方法内部控制台记录单个页面的数据,但是当我尝试访问任何单个值(例如 id)时,我得到旧的无法读取未定义的属性“id”。

Probably not very clearly explained so please see code below:可能解释得不是很清楚,所以请看下面的代码:

PageList.js页面列表.js

import React from 'react';
import { Link } from 'react-router-dom';

const PageList = (props) => {
        const pages = props.pages.map( (page) => {
            return (
                <div key={page.id}>
                    <Link to={`/pagelist/${page.id}`}>{page.title.rendered}</Link>
                </div>                  
            );
        });
        return <div className="page-list">{pages}</div>
};
export default PageList;

PageSingle.js PageSingle.js

import React from 'react';
class PageSingle extends React.Component {
getPage = (props) => {
        let thePage =  props.pages.find(page => page.id === Number(props.match.params.pageId) );
        **console.log(thePage); // 1. this works
        console.log(thePage.id); // 2. this leads to error**
        return thePage;
    };
    render() {
        this.getPage(this.props);
        return (
            <h4>PageSingle</h4>
        )
    }
};
export default PageSingle;

JSON shown in console when it works – I've removed some so as not to take up too much space but you get the idea JSON 工作时显示在控制台中 - 我删除了一些以免占用太多空间,但你明白了

{
content: {rendered: "Test Page 2 Text. Test Page 2 Text. Test Page 2 Text. Test Page 2 Text. Test Page 2 Text. ", protected: false}
date: "2019-09-30T13:38:47"
excerpt: {rendered: "Test Page 2 Text. Test Page 2 Text. Test Page 2 Text. Test Page 2 Text. Test Page 2 Text.", protected: false}
id: 14
link: "http://localhost/all_projects/wordpress/sites_main/my_projects/portfolio/wordpress/test-page-2/"
slug: "test-page-2"
status: "publish"
title: {rendered: "Test Page 2"}
type: "page"
__proto__: Object
}

The props are sent to page single using Browser Router.使用浏览器路由器将道具发送到单页。 The routes themselves are defined in the App.js component and look like this.路由本身在 App.js 组件中定义,如下所示。 Not sure if this is relevant or not, probably not.: Routes不确定这是否相关,可能不是。:路线

<Route 
path="/pagelist" exact
render={ (props) => <PageList {...props} pages={ this.state.pages } /> }
/>
<Route exact 
path="/pagelist/:pageId" 
render={(props) => <PageSingle {...props} pages={ this.state.pages } /> }
/>

Obviously, the end goal is to eventually display the relevant data via the render method but I actually need to access that data before I can do that.显然,最终目标是最终通过渲染方法显示相关数据,但实际上我需要先访问该数据才能做到这一点。 It's probably something really basic that I'm just not understanding.这可能是我不理解的非常基本的东西。 Any pointers in the right direction would be much appreciated.任何指向正确方向的指针都将不胜感激。

Thanks.谢谢。

If you have the correct data in your console.log then I think this is because console.log executes after a small delay, Try doing this and see if you get the property如果您的 console.log 中有正确的数据,那么我认为这是因为 console.log 在一小段延迟后执行,请尝试这样做,看看您是否获得了该属性

setTimeout(function()
 {
   console.log(thePage.id)

 }, 100);

usually keys are added after the console.log call通常在 console.log 调用之后添加键

Hope it helps希望能帮助到你

Okay, for anyone interested, the answer lay in the fact that an array with an object inside of it was being returned in PageSingle.js.好的,对于任何感兴趣的人来说,答案在于一个包含 object 的数组在 PageSingle.js 中返回。

The answer therefore lay in grabbin gthe correct page with an if statement and pushing the required values to an array and then accessing that with bracket notation:因此,答案在于使用 if 语句获取正确的页面,并将所需的值推送到数组,然后使用括号表示法访问它:

    let thisPage = [];

    props.pages.map((page) => {
        if (page.id === Number(props.match.params.pageId)) { 
            thisPage.push(page.id, page.title.rendered, page.content.rendered, page.featured_images);
        }
        return thisPage;
    })

    return (
        <div>
            <h4>{thisPage[1]}</h4>
            <p>{thisPage[2]}</p>
        </div>
    )

Got to be a less convoluted way of doing this though so, any suggestions please let me know.尽管如此,这样做是一种不那么复杂的方式,任何建议请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在本机反应中呈现来自 API 的数据 - Can't Render Data From API in react native 如何使用react-router创建单页应用程序 - How to create a Single Page Application using react-router React.js 使用 Slug 从 API 数据渲染新页面。 (单击文章列表中的一篇文章并直接转到该文章所在的页面) - React.js Render new page from API data using Slug. (click on an article from a list of articles and direct to the page where that article is) 如何使用 React Router 将我当前的 Slick Slider 幻灯片的数据渲染到另一个页面? - How can I render the data of my current Slide of the Slick Slider with click of the button to another page using React Router? 无法使用 React-Router-DOM 将数据从一个页面传递到另一个页面(useHistory,useLocation) - Can't pass data from one page to another with React-Router-DOM (useHistory, useLocation) 如何使用反应路由器将数据从一个页面传递到另一个页面 - How to pass data from a page to another page using react router React api 路由器无法详细显示数据 - React api router can't show data in detail 页面尝试在从 API 加载数据之前呈现 - React - Page tries to render before data is loaded from API - React 没有 React-Router 的 React 中的单页应用程序 - Single Page Application in React without React-Router 如何使用 react-dom-router 在 React 中渲染新页面? - How to render new page in React using react-dom-router?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM