1596779811(1).jpg
2020.8.7一些跨域的问题还没解决,以为离自己很远,没想到就在眼前
首要问题,componentDidMount中请求数据然后渲染页面是没有问题的,但是我想切换城市的时候,重新渲染页面,没有方法了,刚开始是打算在componentDidUpdate中再次渲染,因为state的值改变了嘛,所以打算这么做,但是一弄,页面就疯狂渲染,效果不成功,然后就写了一个方法,内容也是请求数据,点击不同的城市修改接口的参数,然后再点击事件里面重新渲染了,再setstate里面,函数调用这个方法,所以页面再次刷新
2020.8.20错误问题解决
解决方法,把重新请求数据的方法用axios了,不知道为什么ajax的error在我url错误的情况下不去执行error的方法,所以我就换了axios,遇到错误去执行.catch()里面的方法,用了antd messge.error 来提示我们输入城市错误,另外还有我们想在输入框输入之后,清空输入框,用到了那个react refs ,第一次用感觉还行
choseCity() {
let url = `http://www.tianqiapi.com/api?version=v9&appid=23035354&appsecret=8YvlPNrz&city=${this.state.city}`
// window.$.ajax({
// type: 'get',
// url: url,
// error: (data) => {
// return data
// },
// success: (data) => {
// setTimeout(this.setState({
// dataList: data,
// timeList: data.data[this.state.cityNum].hours || [],
// city: data.city,
// indexindex: data.data[this.state.cityNum].index[this.state.dataNum].title || [],
// indexlevel: data.data[this.state.cityNum].index[this.state.dataNum].level || [],
// indexdesc: data.data[this.state.cityNum].index[this.state.dataNum].desc || []
// }), 0)
// },
// })
axios({
url: url,
method: 'get'
})
.then(res => {
setTimeout(this.setState({
dataList: res.data,
timeList: res.data.data[this.state.cityNum].hours || [],
city: res.data.city,
indexindex: res.data.data[this.state.cityNum].index[this.state.dataNum].title || [],
indexlevel: res.data.data[this.state.cityNum].index[this.state.dataNum].level || [],
indexdesc: res.data.data[this.state.cityNum].index[this.state.dataNum].desc || []
}), 0)
})
.catch(error => {
message.error(
'输入错误或城市不存在'
)
})
}
showDetail(item) {
this.setState({
cityNum: item
}, () => {
this.choseCity()
})
}
onMouseOver={this.showDetail.bind(this, index)}
这里来复习一下Refs,就不新建文章来单独写这个了
- 无需导入组件
- 通过调用
React.createRef创建了一个 React ref 并将其赋值给ref变量。 - 通过指定 ref 为 JSX 属性,将其向下传递给 <Search ref={SearchRef}>
- 创建函数,拿到SeachRef清空Search输入框的值
- 在Serach组件的 onSearch调用我们的函数
SearchRef = React.createRef()
clearvalue = () => {
this.SearchRef.current.state.value = ''
}
<Search
ref={this.SearchRef}
placeholder="请输入城市名称,不要带市和区"
onSearch={(e) => {
}, () => {
this.clearvalue()
})
}}
/>
另外,还有一些小问题 想使用请求下来的 数据来做map循环,会报map is not a defind 错误,但是加上 || [] 就ok了
{(this.state.timeList || []).map((item, index) => {
return (
<ul key={index}>
<li >时间:{item.hours}</li>
<li >天气:{item.wea}</li>
<li >温度:{item.tem}℃</li>
<li >风向:{item.win}{item.win_speed}</li>
</ul>
)
})}
2020.8.20已解决:里面使用了两个ant design 组件 下拉框获取option的value值,搜索获取搜索框的值 通过事件名来不同操作
最后这个小项目还有一个bug,就是输入不存在的城市,接口里面就不存在这个城市,所以接口的参数无效,我的页面直接染红












网友评论