将undefined标记转换为preact组件

时间:2017-08-07 13:01:07

标签: javascript html reactjs progressive-web-apps preact

我很擅长预言,我正试图在预制中实施PWA。特别是,此示例应显示人员ID列表。

这是index.html页面:

<!DOCTYPE html>
<html>
  <head>
    <!--Some elements here-->
  </head>
  <body>
    <div id="root">
    </div>
    <script>
    if('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/sw.js', { scope: '/' })
        .then(function(registration) {
              console.log('Service Worker Registered');
        });
      navigator.serviceWorker.ready.then(function(registration) {
         console.log('Service Worker Ready');
      });
    }
    </script>
    //some other scripts
  </body>
</html>

进入src /文件夹有index.js:

import { h, render, Component } from 'preact';
import request from 'superagent';
import Router from 'preact-router';
import Home from './components/homepage';
import PeopleList from './components/people/PeopleList';
import PeopleItem from './components/people/PeopleItem';
import Navigation from './components/navigation';

class Main extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentURL: '/',
      people: {},
    };
    this.setPeople = this.setPeople.bind(this);
    this.onRouteChange = this.onRouteChange.bind(this);
  }

  setPeople({results})
  {
    this.setState({people: results});
  }

  onRouteChange() {
    const pageElement = document.querySelector('.page');
    if (pageElement) {
      pageElement.scrollTop = 0;
      this.setState({
        currentURL: window.location.pathname,
      });
      if(this.state.currentURL == '/people')
      {
        var that = this;
        //webservice api request
        const url = 'https://api.mysite.it/v2/index.php/api/events/people_api_new?id_event=<int>';
        fetch(url,{
          method: 'get',
          headers: {
            //my headers,
          },
        }).then(function(response)
        {
          if(response.status !== 200)
          {
            console.log('server problem');
            return;
          }
          return response.json();
        }).then(function(j){
          console.log(j.people);
          that.setState(
            {
              people: j.people,
            }
          );
        });
        console.log(this.state.people);
      }
      else
      {
         //other
      }
    }
  }


  render(props, state) {
    console.log('render people ' + state.people);
    return (
      <main class="main">
        <div class="page">
            <Router onChange={this.onRouteChange}>
            <Home path="/" />
            <PeopleList path="/people" people={state.people} />
          </Router>
        </div>
        <Navigation currentURL={state.currentURL} />
      </main>
    );
  }
}

render(<Main />, document.getElementById('root'));

我可以忽略导航元素(这是导航菜单,当我点击People元素时,onRouteChange事件应该调用api并在显示该页面之后。

这是PeopleList元素(文件PeopleList.js):

import { h, Component } from 'preact'
import PeopleItem from './PeopleItem'

const PeopleList = ({
  people
}) => (

         <div class="listPeople">
         {
            $.each(people, function(k,v)
            {
                 <PeopleItem person = {v.people_id} />
            })
         }
         </div>
)

export default PeopleList

在这种情况下,人们是一个结构化的对象:

{"1":{"user_id":"1"},"2":{"user_id":"2"} //JSON string of people object came from webservice api

最后,这是PeopleItem元素:

import { h, Component } from 'preact'

const PeopleItem = (person) => (
            <div>
            {
                person
            }
            </div>
    )

export default PeopleItem

当我访问人员页面时,PWA能够读取来自服务器api的人物对象,但是我得到了未定义的标签,而不是PeopleItem元素,如下所示:

<div id="root">
<main class="main">
<div class="page>
<div class="listPeople">
<undefined>
</undefined>
</div>
</div>
</main>
<!-- Navigation element -->
</div>

为什么我在页面上查看未定义的标签?我应该看看:

<div>1</div>
<div>2</div>

而不是:

<undefined></undefined>

2 个答案:

答案 0 :(得分:3)

问题在于:const PeopleItem = (person)

你写的方式,person是道具对象。您需要访问该对象中的person

要做到这一点,你可以像这样去构建道具对象;

const PeopleItem = ({ person }) => (
  <div>{person}</div>
)

或像这样编写PeopleItem:

const PeopleItem = (props) => (
  <div>{props.person}</div>
)

答案 1 :(得分:1)

感谢您的大力帮助。我修改了PeopleList.js和PeopleItem.js,如下所示:

PeopleList.js

import { h, Component } from 'preact'
import PeopleItem from './PeopleItem'

   const PeopleList = (
     props
   ) => (

         <div class="listPeople">
         {
            $.map(props.people, function(k,v)
            {
                 return <PeopleItem person = {v} /> // v is the key and for now i used it as id, after i will modify something.
            })
         }
         </div>
   )

   export default PeopleList

PeopleItem.js

import { h, Component } from 'preact'

const PeopleItem = (props) => (
    <div>{props.people}</div>
)

export default PeopleItem

现在有效!