美文网首页
React之报错笔记及常见交互应用(三)

React之报错笔记及常见交互应用(三)

作者: 喵呜Yuri | 来源:发表于2019-04-26 18:22 被阅读0次

    总结了一些在react项目中遇到的问题
    1.和微信小程序一样的push事件不能直接用
    错误:

          let newCart = this.state.shopcart.push(item);
            this.setState({shopcart:newCart});
    

    正确:

          let newCart = this.state.shopcart;
            let newCartLen = newCart.length;
            newCart[newCartLen] = item;
            this.setState({shopcart:newCart});
    

    2.react是单向数据流,所以这个用法是ok的
    场景:点击增加商品数量

    render:
    <span className="fa fa-plus item" onClick={this.addNum.bind(this,v.songNum)}></span>
    fn:
     addNum(num,e){
            num+=1;
        }
    

    3.input表单赋值
    场景:购物车数量随在input框内添数字改变

    render:
     <input type="text" className="item" value={v.songNum} onChange={this.handleChange.bind(this,v)}/>{v.songNum}
    Fn:
      handleChange(v,event) {
            v.songNum = parseFloat(event.target.value);
            this.setState({shopcart:this.state.shopcart});
        }
    

    错误:

    render:
     <input type="text" className="item" value={v.songNum} onChange={this.handleChange.bind(this,v.songNum)}/>{v.songNum}
    Fn:
      handleChange(v,event) {
            v = parseFloat(event.target.value);
            this.setState({shopcart:this.state.shopcart});
        }
    

    4.多input表单处理


    image.png
    class Tableadd extends Component{
        constructor(props){
            super(props)
            this.state = {
                name:'',
                address:'',
                tel:''
            }
        }
        handleInputChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox' ? target.checked : target.value;
            const name = target.name;
            this.setState({
                [name]: value
            });
            console.log(this.state);
        }
    
        handleChange(){
    
        }
    
        render(){
            return(
                <div className="form-container">
                    <div className="group-row">
                        <span className="title">姓名:</span>
                        <div className="puton-item">
                            <input type="text" name="name" onChange={this.inputchange}/>
                        </div>
                    </div>
                    <div className="group-row">
                        <span className="title">爱好:</span>
                        <div className="puton-item">
                            <select value="lime" onChange={this.handleChange}>
                                <option value="grapefruit">Grapefruit</option>
                                <option value="lime">Lime</option>
                                <option value="coconut">Coconut</option>
                                <option value="mango">Mango</option>
                            </select>
                        </div>
                    </div>
                    <div className="group-row">
                        <span className="title">地址:</span>
                        <div className="puton-item">
                            <input type="text" name="address" onChange={this.inputchange}/>
                        </div>
                    </div>
                    <div className="group-row">
                        <span className="title">电话:</span>
                        <div className="puton-item">
                            <input type="text" name="tel" onChange={this.inputchange}/>
                        </div>
                    </div>
                </div>
            )
        }
    }
    
    
    export default Tableadd;
    

    当然你也可以不用state定义变量,写在redux中直接取也可以的

    5.es6箭头函数

     componentDidMount(){
          this.timer = setInterval(()=>this.tick(),1000);
          console.log(this);
        }
    

    为什么箭头函数就可以直接在this函数中接着写this不报错呢?
    箭头函数的this定义:箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的。简单的说,函数在定义时,this就继承了定义函数的对象。
    https://www.jianshu.com/p/c1ee12a328d2

    7.点击,带参点击

    <i className="plus iconfont icon-jiahao" onClick={this.addtocartFn(this, item)}></i>
    

    这个方法在页面加载之初就循环了二十多遍。。因为没绑定bind
    应该这样写啊:

    不带参的:
    <i className="plus iconfont icon-jiahao" onClick={this.deltocartFn}></i>
    带参的:
    <i className="plus iconfont icon-jiahao" onClick={this.addtocartFn.bind(this, item)}></i>
    

    8.动态className

     <i className={"plus iconfont icon-jiahao "+(item.num!=0?"none":"block")} ></i>
     <i className={"del iconfont icon-jiahao "+(item.num==0?"none":"block")} ></i>
    

    9.table的用法:
    以下这种是会报错的,必须由tbody包含

     <table>
                            <tr>
                                <td></td>
                            </tr>
    </table>
    

    10.公共方法引用
    common.js:

    import  'whatwg-fetch'
    import {toggleloading} from './../redux/action/layer'
    
    expor const sampleFn = ()=>{
    
    }
    
    export const fetchPosts = (postTitle,Fn) => (dispatch, getState) => {
        dispatch(toggleloading(true));
        return fetch(postTitle)
            .then(response => response.json())
            .then(json => {
                setTimeout(()=>{
                    dispatch(toggleloading(false));
                    return Fn(json);
                },1000)
            });
    }
    

    普通公共方法就直接应用就可以了,异步action方法需要在mapDispatchToProps函数中注入需要使用的公共方法

    引用到页面:

    import {fetchPosts,sampleFn} from '../../lib/common'
    
    class Shop extends Component{
        componentWillMount(){
    
            sampleFn();
    
            this.props.fetchPosts('/api/data.json',(res)=>{
                this.props.getgoodlist(res.data.songs);
            })
        }
    
      render(){
          return(
              ...
            )
          }
    }
    
    const mapStateToProps = (state) =>({
       ...
    })
    const mapDispatchToProps = (dispatch) =>({
        ...
        fetchPosts:(url,fn)=>dispatch(fetchPosts(url,fn))
    })
    
    export default connect(mapStateToProps,mapDispatchToProps)(Shop);
    

    11.报错Proxy error
    本来用的好好的,今早起来发现数据无法获取

    Proxy error: Could not proxy request /api/data.json from localhost:3000 to localhost:5000 (ENOTFOUND).
    

    找到占用5000端口的pid

    netstat -aon|findstr “7000”
    
    image.png

    14112就是node.exe,找到592就是金山词霸。。。额,金山词霸右键点击结束进程


    image.png

    但还是不行,我改了一下proxy

    "proxy": {
        "/api": {
          "target": "http://192.168.31.1:5000"  //这儿以前是 "http://localhost:5000
    "
        }
      }
    

    就好了
    12.返回页面
    这个除了Link标签以外当然也需要点击返回或跳转了

    this.props.history.push('/shop')    返回指定页面
    this.props.history.goBack()  返回上一页
    this.props.history.go(-2)   返回上上一页
    

    这几个方法不会刷新目标页,但是都会触发目标页面的componentWillMount()

    13.定时器
    一进来定时器就启动,返回首页时停止。这个this.interval属于该class的全局方法,不止可以在 componentDidMount()中定义,也可以在方法中定义,因为我们也会有点击按钮启动定时器的业务场景

        componentDidMount() {
            this.interval = setInterval(() => this.tick(), 1000);
        }
        tick=()=>{
            console.log('kk--');
        }
        goShopIndex=()=>{
            clearInterval(this.interval);
            this.props.history.goBack()
        }
    

    相关文章

      网友评论

          本文标题:React之报错笔记及常见交互应用(三)

          本文链接:https://www.haomeiwen.com/subject/kafvmqtx.html