簡體   English   中英

JSX 無法正確渲染

[英]JSX won't render properly

我的 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;

PS我是學生

這就是你要找的。 表達式+{}被評估為NaN 但請使用列表渲染。

        const image = `<img src= ${+posts[i].image} />`;
                                   ^ here

似乎您正在嘗試構建一個字符串,然后將其存儲在狀態中並在更新后呈現該字符串。 不幸的是,這不是你應該如何使用 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;

您甚至可以通過將卡片元素也作為組件來使它更好一些。 而且由於它沒有任何功能(還)它只需要控制輸出。

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>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM