淘先锋技术网

首页 1 2 3 4 5 6 7

1:axios不支持jsonp

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
// https://github.com/webmodules/jsonp包
import oldJSONP from 'jsonp'

function jsonp(url, opts = {}) {
    return new Promise((resolve, reject) => {
        //url是jsonp请求的路径,opts是请求的属性,第三个参数是成功回调
        oldJSONP(url, opts, function (err, data) {
            if (err) reject(err)
            resolve(data)
        })
    })
}

//async + await(后跟promise,有await,就需要async来修饰该函数)
class Search extends Component {
    //页面加载完毕之后加载这个方法
    // async componentDidMount(){
    //     //{param:'cb'}是百度搜多规定的
    //     let result=await jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a',{param:'cb'})
    //     // console.log(result)
    //     // return result
    // }
    constructor() {
        super()
        this.state = {
            val: '',
            arry: [, , , ],
            index: -
        }
    }

    handleChange = async (e) => {
        let str = e.target.value
        //解构赋值
        var {s} = await jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + str, {param: 'cb'})
        this.setState({
            val: str,
            arry: s
        })
    }
    changeIndex = (e) => {
        let index = this.state.index
        if (e.keyCode ===  || e.keyCode === ) {
            if (e.keyCode === ) {
                index--
            } else {
                index++
            }
            this.setState({
                index,
                val: this.state.arry[index]
            })

        }
    }

    render() {
        return (
            <div className={'container'}>
                <div className={'panel panel-default'}>
                    <div className={'panel-heading'}>
                        <div className="input-group">
                            {/*input后面必须写/,否则会报错*/}
                            <input type="text" className="form-control" placeholder="Search for... "
                                   value={this.state.val} onChange={this.handleChange} onKeyDown={this.changeIndex}/>
                        </div>
                    </div>
                    <div className={'panel-body'}>
                        <ul className={"list-group"}>
                            {
                                this.state.arry.map((item,index) => {
                                    // 这里一定要加return
                                   return <li className={index==this.state.index?'active list-group-item':'list-group-item'} key={index}><span>{item}</span></li>
                                })
                            }
                        </ul>
                    </div>
                </div>
            </div>
        )
    }
}

ReactDOM.render(
    <Search></Search>
    , document.getElementById('root'))

这里写图片描述