JSX无法正确呈现

时间:2020-08-27 12:44:23

标签: javascript reactjs concatenation jsx

我的JSX无法在我的React网页上正确显示,而是得到以下输出:

<div class='card'>NaNSasha<img src= NaN />Boddy Cane</div>.

组件:

import React,  {Component} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component{

  state = {

    string : '',
  }

  componentDidMount(){

     let posts = [

        {
          title: 'somebody toucha my spaghet',
          author: 'Karen',
          image:'https://media-cdn.tripadvisor.com/media/photo-s/11/69/c7/f9/spagetti.jpg',
          location: 'Jimmy John',
          description: 'This spagetti is amazing'
        },
        {
          title: `I love food`,
          author: 'Sasha',
          image:'https://hoodline.imgix.net/uploads/story/image/610603/donuts2.jpg?auto=format',
          location: 'Boddy Cane',
          description: 'cjndwsijnjcinjw'
        }
    
  ];

      for(let i =0; i < posts.length; i ++){

        const header = `<div class='card'>${+posts[i].title}`;
        const body = posts[i].author;
        const image = `<img src= ${+posts[i].image} />`;
        const description = `${posts[i].location}</div>`;
  
        const concatThis = header + body + image + description
        this.setState({
  
          string: concatThis
        });
      };
    };
    
  render(){

    return(

      <div className='container'>
      {this.state.string}
      </div>
      
    
    )
  }
}

export default App;

我是学生

2 个答案:

答案 0 :(得分:1)

这就是您要寻找的。表达式NaN的计算结果为 const image = `<img src= ${+posts[i].image} />`; ^ here 。但是请使用列表渲染。

number <- ""
number.append(randomDigit(1,9))
repeat 29 times
  number.append(randomDigit(0,9))
end repeat

答案 1 :(得分:0)

似乎您正在尝试构建一个字符串,然后将该字符串存储在一个状态中,并在更新后呈现该字符串。不幸的是,这不是应该使用React的方式。

state只能是原始数据,例如带有对象的posts数组。它保留了组件的内容和数据,并且不应将自己与其他任务相关。显然,您可以将任何类型的数据置于状态中,例如字符串。

state = {
  title: 'My food blog',
  description: 'Awesome stuff about food',
  posts: [
    {
      title: 'somebody toucha my spaghet',
      author: 'Karen',
      image:'https://media-cdn.tripadvisor.com/media/photo-s/11/69/c7/f9/spagetti.jpg',
      location: 'Jimmy John',
      description: 'This spagetti is amazing'
    },
    {
      title: `I love food`,
      author: 'Sasha',
      image:'https://hoodline.imgix.net/uploads/story/image/610603/donuts2.jpg?auto=format',
      location: 'Boddy Cane',
      description: 'cjndwsijnjcinjw'
    }
  ]
}

只要将组件放置在页面上并且现在可以工作,就会触发componentDidMount方法。在其中,您可以执行更改数据或从服务器下载数据之类的操作。您应该在那里进行操作是有道理的,因为这样您将首先显示您的组件,也许显示它正在加载,然后从服务器获取数据。完成之后,使用新数据更新组件的状态,并且将使用新数据调用render方法。例如(出于说明目的):

componentDidMount() {
  fetch('urlofdatathatyouwant') // Uses AJAX to get data from anywhere you want with the Fetch API.
    .then(response => response.json()) // Tells it to read turn the response from JSON into an usable JavaScript values.
    .then(data => {
      this.setState({
        posts: data // Use the new data to replace the posts. This will trigger a new render.
      });
    });
}

render方法应主要关注您所在状态下数据的呈现。在这种情况下,它应该遍历处于posts状态的元素,并为每个帖子创建一个React元素。

render() {
  const { posts } = this.state;
  return(
    <div className='container'>
      {posts.map(({ title, author, image, location, description }) => ( 
        // Loop over each post and return a card element with the data inserted.
        <div className="card">
          <span>{title}</span>
          <span>{author}</span>
          <img src={image} alt={title}/>
          <span>{location}</span>
          <span>{description}</span>
        </div>
      ))}
    </div>
  )
}

所有内容放在一起,如下例所示。因此,状态仅保存数据,componentDidMount是在组件在页面上之后处理数据的地方,而render仅输出需要使用JSX创建的HTML。

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

class App extends Component{

  state = {
    posts: [
      {
        title: 'somebody toucha my spaghet',
        author: 'Karen',
        image:'https://media-cdn.tripadvisor.com/media/photo-s/11/69/c7/f9/spagetti.jpg',
        location: 'Jimmy John',
        description: 'This spagetti is amazing'
      },
      {
        title: `I love food`,
        author: 'Sasha',
        image:'https://hoodline.imgix.net/uploads/story/image/610603/donuts2.jpg?auto=format',
        location: 'Boddy Cane',
        description: 'cjndwsijnjcinjw'
      }
    ]
  }

  componentDidMount() {
    // Do something here with the posts if you need to.
  }
    
  render() {
    const { posts } = this.state;
    return(
      <div className='container'>
        {posts.map(({ title, author, image, location, description }, index) => (
          <div key={index} className="card">
            <span>{title}</span>
            <span>{author}</span>
            <img src={image} alt={title}/>
            <span>{location}</span>
            <span>{description}</span>
          </div>
        ))}
      </div>
    )
  }
}

export default App;

通过将card元素也设置为组件,您甚至可以使它更好一点。而且由于它还没有任何功能,所以只需要控制输出即可。

const Card = ({ title, author, image, location }) => (
  <div className="card">
    <span>{title}</span>
    <span>{author}</span>
    <img src={image} alt={title}/>
    <span>{location}</span>
    <span>{description}</span>
  </div>
)

然后将卡导入到App组件中,并在render方法中使用它。

// App.jsx render.
render() {
  const { posts } = this.state;
  return(
    <div className='container'>
      { /* ...post taking all the properties of each post and passes them to the card element */ }
      {posts.map((post, index) => <Card key={index} {...post} />)} 
    </div>
  )
}