JSX的列表渲染
在开始介绍远程数据请求前,先对JSX的列表渲染做下介绍,给JSX不熟悉的朋友提供便利。
构建数组对象
先使用JS的基本语法,打开blog.jsx文件然后再blog方法里编写代码:
const girls = [
{id:1,name:'胡一菲'},
{id:2,name:'陈美嘉'},
{id:3,name:'诸葛大力'},
{id:4,name:'咖喱酱'}
]
在JSX代码中渲染列表
blog.jsx的全部代码
import Taro ,{useState ,useEffect}from '@tarojs/taro'
import {View , Text ,Button,Image} from '@tarojs/components'
import {xiedajiao,liuying} from '../../tools'
function Blog(){
useEffect(()=>{
xiedajiao()
liuying()
},[])
·
const girls = [
{id:1,name:'胡一菲'},
{id:2,name:'陈美嘉'},
{id:3,name:'诸葛大力'},
{id:4,name:'咖喱酱'}
]
const [blogTitle,setBlogTitle]=useState('JSPangBlog')
const [introduce,setIntroduce]=useState('111111')
const gotoIndex=()=>{
Taro.navigateTo({url:'/pages/index/index?blogTitle='+blogTitle+'&introduce='+introduce})
}
return (
<View>
<Text>Blog Page111</Text>
<Button onClick={gotoIndex}>我要去Index页面</Button>
<View>
{ girls.map((item,index)=>{
return (
<View>{item.name}</View>
)
}) }
</View>
</View>
)
}
在JSX中使用逻辑判断
在JSX中使用逻辑判断,不能像下边这样用判断:
<view>
{
if(zhujueNum===1){
return ('张伟')
}else{
return('吕子乔')
}
}
</view>
需要使用判断要用三目运算符:
<view>
男主角是:{zhujueNum==1?'张伟':'吕子乔'}
</view>
或者也可以使用,短路运算符:
<view>
男主角是:{zhujueNum==1 && '张伟' || '吕子乔'}
</view>
请求远程数据
Taro的远程数据请求,利用Taro的request的方式,这里给出request的参数文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
下边我们在blog.jsx文件中,编写一个testHandler方法,方法中使用Taro.request后去远端数据,这里数据请求的路径url,你可以去mockJs网站,也可以自己用node等方式创建一个数据请求路径,或者你项目开发时候的路径
const getData= ()=>{
Taro.request({
url:'...'
}).then(res=>{
console.log(res.data)
})
}
然后在JSX中编写一个按钮,加上onClick事件,代码如下:
<Button onClick={getData}>获取数据</Button>
遍历渲染获取到的数据
先用useState声明一个articleList,代码如下:
const [articleList,setArticleList] = useState([])
然后在return中使用map进行遍历,如下:
{
articleList.map((item,index)=>{
return (<View key={index}>- {item.title} </View>)
})
}
blog.jsx完整的代码:
import Taro, { useState } from '@tarojs/taro'
import { View, Text, Button } from '@tarojs/components'
function Blog2(){
const [dataList, setDataList] = useState([])
const getData = () => {
Taro.request({
url: 'https://apiblog.jspang.com/default/getArticleList'
})
.then((res)=>{
console.log(res.data)
setDataList(res.data.list)
})
}
return (
<View>
<View><Text>数据请求</Text></View>
<Button onClick={getData} >获取数据</Button>
<View>
{
dataList.map((item, index)=>{
return (
<View key={index} >{item.title}</View>
)
})
}
</View>
</View>
)
}
export default Blog2