React学习17----项目练习,外卖详情页,react解析html

除了上面的学的之外
react解析html

如果接口返回一个html标签
例如

八宝酱菜

这样解析出来:

八宝酱菜

}}>

参考文档:
https://reactjs.org/docs/dom-elements.html

具体项目如下:
在 https://blog.csdn.net/zhaihaohao1/article/details/87928738
的基础上写详情页
效果图:
React学习17----项目练习,外卖详情页,react解析html_第1张图片

项目结构:

React学习17----项目练习,外卖详情页,react解析html_第2张图片

项目中:
App.js
ProductList.js
index.css
和上一篇是一样的
这里只贴出详情页代码:ProductDetails.js

import React from 'react';
import axios from 'axios';
import {BrowserRouter as Router, Route, Link} from "react-router-dom";
/*
react解析html
    https://reactjs.org/docs/dom-elements.html
    
*/ class ProductDetails extends React.Component{ constructor(props){ super(props); this.state = { title:'ProductDetails', list: [], port: 'http://a.itying.com/', } } // 请求数据 httpRequest=(id)=>{ let url = this.state.port+'api/productcontent?id='+id; axios.get(url) .then((response)=> { //请求成功 console.log(response); // 把请求到的数据,赋值给构造函数的数据 this.setState({ // list 会自动转成一个对象 list:response.data.result[0], }) console.log(this.state.list); }) .catch(function (error) { //请求失败 console.log(error); }); } // 生命周期的方法,组件加载的时候调用 componentDidMount=()=>{ console.log(this.props.match.params.id); let id = this.props.match.params.id; this.httpRequest(id); } render() { return(
返回

{this.state.list.title}

{this.state.list.price}/份

商品详情

数量:
-
+
); } } export default ProductDetails;

注意事项:
1.404错误:
React学习17----项目练习,外卖详情页,react解析html_第3张图片

当渲染界面 触发 render 的时候,数据还未请求成功(异步请求)
所以 img 标签中的路径是个域名,所以报404错误,
当数据请求到时,改变构造方法中的数据,会自动重新调用 render 渲染数据,
所以图片显示正常。

解决方法:判断一下就可以了,
把:
${this.state.port}${this.state.list.img_url}} />
改成
{this.state.list.img_url?${this.state.domain}${this.state.list.img_url}} />:""}
就可以了;

2.注意定义的list;
list可以定义成,对象(list:{}),或数组([])(数组也是对象),字符串不能点方法

源码下载:
rdemo17_3
https://download.csdn.net/download/zhaihaohao1/10980497

你可能感兴趣的:(React)